/**
 * 用户管理模块
 * @type {[type]}
 */
var userListModule = angular.module("UserListModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns']);  //'ui.grid.exporter': grid's div need to add new directive:ui-grid-exporter  -> 'ui.grid.cellNav',
userListModule.controller('UserListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, UserService, $rootScope, Store) {
  
  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true,
    showMenu:false
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    if ($stateParams.reset) {
      Store.localRemove('userSearch');
    } else {
      var lastSearch = JSON.parse(Store.localGet('userSearch') || '{}');
      paginationOptions.pageNumber = lastSearch.currentPage || 1; 
      paginationOptions.pageSize = lastSearch.pageSize; 
      $scope.user.userName = lastSearch.userName || '';
      $scope.user.nickName = lastSearch.nickName || '';
      $('#beginCreateTime').val(lastSearch.startDate || '');
      $('#endCreateTime').val(lastSearch.endDate || '');
      $scope.user.userId = lastSearch.userId || 0;
      $scope.user.mobileNumber = lastSearch.mobileNumber || '';
      $scope.user.rid = lastSearch.rid || '';
      $scope.gridOptions.paginationCurrentPage = paginationOptions.pageNumber;
    }
    $scope.gridApi = gridApi; 
    $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
      if (sortColumns.length === 0) {
        paginationOptions.sort = null;
      }else{
        paginationOptions.sort = sortColumns[0].sort.direction;
      }
      getPage();
    });

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'icon',
      displayName: '头像',
      width:80,
      cellTemplate: '<a href="javascript:void(0)" title="用户名：{{row.entity.userName}}&#10;昵称：{{row.entity.nickName}}&#10;邮箱：{{row.entity.emailAddress}}"><img ng-if="COL_FIELD" ng-src="{{COL_FIELD}}?w=28" class="article-icon"><img ng-if="!COL_FIELD" src="images/defaultIcon.jpg" class="article-icon"></a>'
    }, {
      field: 'userName',
      displayName: '用户名',
      width:180
    },{
      field: 'nickName',
      displayName: '昵称',
      width:100
    },{
      field: 'model',
      displayName: '类型',
      width:80,
      cellFilter:'mapUserType'
    }, {
      name: 'userId',
      displayName: '操作',
      width: 240,
      cellTemplate: '<a class="btn-small" href="#/user/edit/{{COL_FIELD}}">修改</a><span ng-if="row.entity.model===1">&nbsp;&nbsp;&nbsp;<a class="btn-small" href="#/user/level/{{COL_FIELD}}/update">设置用户级别</a></span><span ng-if="row.entity.model===2">&nbsp;&nbsp;&nbsp;<a class="btn-small" href="#/user/agentlevel/{{COL_FIELD}}/update">设置代理商级别</a></span>&nbsp;&nbsp;&nbsp;<a class="btn-small" href="#/user/{{COL_FIELD}}/relation">设置推荐人</a>',
      enableFiltering: false
    }, {
      field: 'level',
      displayName: '用户等级',
      width:100
    }, {
      field: 'spreadLevel',
      displayName: '传播等级',
      width:100
    }, {
      field: 'rid',
      displayName: '推荐人',
      width:100
    }, {
      field: 'sex',
      displayName: '性别',   
      width:80,
      cellFilter: 'mapUserGender'
    }, {
      field: 'emailAddress',
      displayName: '邮箱',
      width:140
    }, {
      field: 'mobileNumber',
      displayName: '手机号',
      width:140,
      cellFilter: 'mobileFilter'
    }, {
      field: 'bornDate',
      displayName: '出生年月',
      width:120
    }, {
      field: 'follow',
      displayName: '关注状态',
      width:100,
      cellFilter: 'mapUserFollow'
    }, {
      field: 'createAt',
      displayName: '创建日期',
      width:120
    }
  ];

  $scope.user = {};

  //分页查询
  var getPage = function() {
    var form = {
      currentPage: paginationOptions.pageNumber, 
      pageSize: paginationOptions.pageSize, 
      userName: $scope.user.userName || '',
      nickName: $scope.user.nickName || '',
      startDate: $('#beginCreateTime').val(),
      endDate: $('#endCreateTime').val(),
      userId: $scope.user.userId || 0,
      mobileNumber: $scope.user.mobileNumber || '',
      rid: $scope.user.rid || ''
    };
    UserService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var users = data.users || [];
      angular.forEach(users, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm");
        item.icon = Yihu.util.setContext($scope.downloadUrl, item.icon ? item.icon : '');
        if(item.icon.indexOf($scope.downloadUrl) > -1 && item.icon.indexOf('wx.qlogo.cn') > 0) {
          item.icon = item.icon.replace($scope.downloadUrl, '');
        }
      });
      $scope.gridOptions.data = users;
      Store.localSave('userSearch', JSON.stringify(form));
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };
  
  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.userId;

        UserService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };

})
userListModule.controller('UserListViewCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, UserService, $rootScope, Store) {
  
  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true,
    showMenu:false
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    if ($stateParams.reset) {
      Store.localRemove('userSearch');
    } else {
      var lastSearch = JSON.parse(Store.localGet('userSearch') || '{}');
      paginationOptions.pageNumber = lastSearch.currentPage || 1; 
      paginationOptions.pageSize = lastSearch.pageSize; 
      $scope.user.userName = lastSearch.userName || '';
      $scope.user.nickName = lastSearch.nickName || '';
      $('#beginCreateTime').val(lastSearch.startDate || '');
      $('#endCreateTime').val(lastSearch.endDate || '');
      $scope.user.userId = lastSearch.userId || 0;
      $scope.user.mobileNumber = lastSearch.mobileNumber || '';
      $scope.user.rid = lastSearch.rid || '';
      $scope.gridOptions.paginationCurrentPage = paginationOptions.pageNumber;
    }
    $scope.gridApi = gridApi; 
    $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
      if (sortColumns.length === 0) {
        paginationOptions.sort = null;
      }else{
        paginationOptions.sort = sortColumns[0].sort.direction;
      }
      getPage();
    });

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'icon',
      displayName: '头像',
      width:80,
      cellTemplate: '<a href="javascript:void(0)" title="用户名：{{row.entity.userName}}&#10;昵称：{{row.entity.nickName}}&#10;邮箱：{{row.entity.emailAddress}}"><img ng-if="COL_FIELD" ng-src="{{COL_FIELD}}?w=28" class="article-icon"><img ng-if="!COL_FIELD" src="images/defaultIcon.jpg" class="article-icon"></a>'
    }, {
      field: 'userName',
      displayName: '用户名',
      width:180
    },{
      field: 'nickName',
      displayName: '昵称',
      width:100
    },{
      field: 'model',
      displayName: '类型',
      width:80,
      cellFilter:'mapUserType'
    }, {
      field: 'level',
      displayName: '用户等级',
      width:100
    }, {
      field: 'spreadLevel',
      displayName: '传播等级',
      width:100
    }, {
      field: 'rid',
      displayName: '推荐人',
      width:100
    }, {
      field: 'sex',
      displayName: '性别',   
      width:80,
      cellFilter: 'mapUserGender'
    }, {
      field: 'emailAddress',
      displayName: '邮箱',
      width:140
    }, {
      field: 'mobileNumber',
      displayName: '手机号',
      width:140,
      cellFilter: 'mobileFilter'
    }, {
      field: 'bornDate',
      displayName: '出生年月',
      width:120
    }, {
      field: 'follow',
      displayName: '关注状态',
      width:100,
      cellFilter: 'mapUserFollow'
    }, {
      field: 'createAt',
      displayName: '创建日期',
      width:120
    }
  ];

  $scope.user = {};

  //分页查询
  var getPage = function() {
    var form = {
      currentPage: paginationOptions.pageNumber, 
      pageSize: paginationOptions.pageSize, 
      userName: $scope.user.userName || '',
      nickName: $scope.user.nickName || '',
      startDate: $('#beginCreateTime').val(),
      endDate: $('#endCreateTime').val(),
      userId: $scope.user.userId || 0,
      mobileNumber: $scope.user.mobileNumber || '',
      rid: $scope.user.rid || ''
    };
    UserService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var users = data.users || [];
      angular.forEach(users, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm");
        item.icon = Yihu.util.setContext($scope.downloadUrl, item.icon ? item.icon : '');
        if(item.icon.indexOf($scope.downloadUrl) > -1 && item.icon.indexOf('wx.qlogo.cn') > 0) {
          item.icon = item.icon.replace($scope.downloadUrl, '');
        }
      });
      $scope.gridOptions.data = users;
      Store.localSave('userSearch', JSON.stringify(form));
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };
  
  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.userId;

        UserService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };

})
.filter('mapUserType', function(){
  var userTypeHash = {
    0:'系统用户',
    1:'普通用户',
    2:'代理商'
  };
  return function(input){
    return userTypeHash[input];
  };
})
.filter('mapUserGender', function(){
  var userGenderHash = {
    1:'男',
    2:'女'
  };
  return function(input){
    if(!input){
      return '';
    }
    return userGenderHash[input];
  };
})
.filter('mapUserFollow', function(){
  var userHash = {
    0:'未关注',
    1:'已关注',
    2:'取消关注'
  };
  return function(input){
    return userHash[input];
  };
})
.controller('AddUserCtrl', function($scope, $state, UserService, $rootScope, Upload, $timeout, DataDictService){
  $scope.UserForm = {
    title:"新增用户"
  };

  $scope.user = {
    typeList:[{
      value:0,
      text:"系统用户"
    }],
    sex: '1',
    model: '0'
  };

  $timeout(function(){
    DataDictService.getChildren({
      parentPath: 'cms/config/userspreadlevel'
    }, function(data){
      $scope.user.spreadLevels = data.childrens;
      $timeout(function() {
        $scope.user.spreadLevel = 'lv1';
      }, 20);
    });
  }, 1000);

  // upload on file select or drop
  $scope.upload = function (file) {
    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      // console.log(items instanceof Array);
      var data = resp.data;
      if(data.code===0){
        $timeout(function(){
          $scope.user.icon = data.url+"?w=80";
          $scope.user.urls = data.id;
        });
      }
    }, function (resp) {
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progressPercentage + '% ');
    });
  };

  $scope.submitForm = function(){
    var form = {
      userName: $scope.user.userName,
      nickName: $scope.user.nickName,
      password: $scope.user.password,
      emailAddress: $scope.user.emailAddress,
      mobileNumber: $scope.user.mobileNumber,
      bornDate: $('#bornDate').val(),
      sex: $("input[name='sex']").prop('checked') ? '1' : '2',
      model: $scope.user.model,
      icon: $scope.user.urls,
      spreadLevel: $scope.user.spreadLevel || ''
    };
    UserService.create({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditUserCtrl', function($scope, $state, $timeout, User, UserService, $rootScope, Upload, DataDictService){
  $scope.UserForm = {
    title:"更新用户"
  };

  $scope.user = {
    typeList:[{
      value:1,
      text:"普通用户"
    },{
      value:2,
      text:"代理商"
    },{
      value:0,
      text:"系统用户"
    }]
  };
  angular.extend($scope.user, User||{});
  $scope.user.icon = Yihu.util.setContext($scope.downloadUrl, User.icon ? User.icon+"?w=80" : '');
  if($scope.user.icon.indexOf($scope.downloadUrl) > -1 && $scope.user.icon.indexOf('wx.qlogo.cn') > 0) {
    $scope.user.icon = $scope.user.icon.replace($scope.downloadUrl, '');
  }

  var watcher = $scope.$watch("user", function(newValue, oldValue){
    watcher();
    angular.extend($scope.user, User||{});

    $timeout(function(){
      $scope.user.model = User.model + '';
      $scope.user.gender = User.sex;
      $scope.user.icon = Yihu.util.setContext($scope.downloadUrl, User.icon ? User.icon+"?w=80" : '');
      if($scope.user.icon.indexOf($scope.downloadUrl) > -1 && $scope.user.icon.indexOf('wx.qlogo.cn') > 0) {
        $scope.user.icon = $scope.user.icon.replace($scope.downloadUrl, '');
      }
      DataDictService.getChildren({
        parentPath: 'cms/config/userspreadlevel'
      }, function(data){
        $scope.user.spreadLevels = data.childrens;
      });
      DataDictService.getChildren({
        parentPath: 'cms/config/agentspreadlevel'
      }, function(data){
        $scope.user.agentSpreadLevels = data.childrens;
      });
    }, 50);

    $timeout(function(){
      $scope.user.agentSpreadLevel = User.spreadLevel || '';
    }, 500);
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      // console.log(items instanceof Array);
      var data = resp.data;
      if(data.code===0){
        $timeout(function(){
          $scope.user.icon = data.url+"?w=80";
          $scope.user.urls = data.id;
        });
      }
    }, function (resp) {
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progressPercentage + '% ');
    });
  };

  $scope.submitForm = function(){
    var form = {
      userName: $scope.user.userName,
      nickName: $scope.user.nickName,
      password: $scope.user.password,
      emailAddress: $scope.user.emailAddress,
      mobileNumber: $scope.user.mobileNumber,
      bornDate: $('#bornDate').val(),
      model: $scope.user.model,
      icon: $scope.user.urls,
      spreadLevel: $scope.user.agentSpreadLevel || '',
      rid: $scope.user.rid || 0
    };
    var repwd = $scope.user.repassword;
    if (repwd && form.password != repwd) {
      alert('两次输入的密码不一致！');
      return;
    } else if (repwd) {
      form.password = md5(repwd);
    }
    UserService.update({id:$state.params.id}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('ChangePwdCtrl', function($scope, $state, UserService, $rootScope){
  $scope.UserForm = {
    title:"修改密码"
  };

  $scope.changePwd = function(user){
    if(!user.oldpassword || !user.password){
      return;
    }

    var userForm = {
      userName: $scope.currentUser.userName,
      password: md5(user.oldpassword),
      newPassword: md5(user.password)
    };

    UserService.changePwd({}, userForm, function(data){
      if(data && data.result==1){
        $scope.UserForm.error = "密码错误或网络故障，请稍候再试！";
        return;
      }
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });

  };
})
.controller('UpdateLevelCtrl', function($scope, $state, UserService, $rootScope, User, $timeout, DataDictService){
  $scope.UserForm = {
    title:"设置级别"
  };

  $scope.user = User || {};
  var watcher = $scope.$watch("user", function(newValue, oldValue){
    watcher();
    $scope.user = User || {};
  });

  $timeout(function(){
    var userLevel = {"lv02": "冻结用户", "lv01": "降级用户", "lv0": "普通会员", "lv1": "皇冠一星", "lv2": "皇冠二星", "lv3": "皇冠三星", "lv4": "皇冠四星", "lv5": "皇冠五星"};
    var agentLevel = {"lv1": "皇冠一星", "lv2": "皇冠二星", "lv3": "皇冠三星", "lv4": "皇冠四星", "lv5": "皇冠五星"};
    var level = $scope.user.level;
    if($scope.user.model === 1) {
      DataDictService.getChildren({
        parentPath: 'cms/config/userlevel'
      }, function(data){
        $scope.user.userLevelList = data.childrens;

        $timeout(function(){
          $scope.user.userlevel = level;
        }, 20);
      });
      $scope.user.currentLevel = userLevel[level];
    } else if($scope.user.model === 2) {
      DataDictService.getChildren({
        parentPath: 'cms/config/agentlevel'
      }, function(data){
        $scope.user.agentLevelList = data.childrens;
        $timeout(function(){
          $scope.user.agentlevel = level;
        }, 20);
      });
      $scope.user.currentLevel = agentLevel[level];
    }
  }, 500);

  $scope.updateLevel = function(user){
    if ($scope.user.model === 1) {
      //普通用户
      UserService.setUserLevel({}, {
        userId: $scope.user.userId,
        level: $scope.user.userlevel
      }, function(data){
        $rootScope.currentAnimated = !$rootScope.currentAnimated;
        $state.go('^');
      });
    } else if($scope.user.model === 2) {
      //供应商
      UserService.setAgentLevel({}, {
        userId: $scope.user.userId,
        level: $scope.user.agentlevel
      }, function(data){
        $rootScope.currentAnimated = !$rootScope.currentAnimated;
        $state.go('^');
      });
    }
  };
})

.controller('UpdateRelationCtrl', function($scope, $state, UserService, $rootScope, User, $timeout, DataDictService){
  $scope.UserForm = {
    title:"设置推荐人"
  };

  $scope.user = User || {};
  var watcher = $scope.$watch("user", function(newValue, oldValue){
    watcher();
    $scope.user = User || {};
  });

  $scope.submitForm = function(){
    UserService.update({
      id:$state.params.id
    }, {
      rid: $scope.user.rid
    }, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
    
  };
})
.controller('ViewUserCtrl', function($scope, $state, UserService, $rootScope, User){
  $scope.Form = {
    title:"用户详情"
  };
  $scope.user = User || {};
  var watcher = $scope.$watch("user", function(newValue, oldValue){
    watcher();
    $scope.user = User || {};
    var nickname = $scope.user.nickName;
    $scope.user.userName = nickname ? Base64.decode(nickname) : $scope.user.userName;
    $scope.user.createAt = moment($scope.user.createAt).format("YYYY-MM-DD HH:mm:ss");
  });

  $scope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    window.history.back();
  };
})

/**
 * 用户登录控制器
 */
.controller('UserLoginCtrl', function($scope, $rootScope, $stateParams, AUTH_EVENTS, AuthService, Store, UserService){
  var userName = Store.get("uname");
  $scope.formOption = {
    title: "用户登录",
    error:''
  };

  $scope.user = {
    userName: userName || '',
    remember: !!userName
  };

  $scope.login = function (credentials) {
    if($("input[name='remember']").prop('checked')){
      Store.save("uname", credentials.userName, 90*24*3600000);
    }

    AuthService.login(credentials).then(function(user) {
      if(!user.userId){
        $scope.formOption.error = "用户名或密码错误！";
      }else{
        $scope.setCurrentUser(user);

        UserService.getUserPriviledge({userId: user.userId}, function(data){
          $rootScope.userPriviledges = data || [];
        });
        $rootScope.$broadcast(AUTH_EVENTS.loginSuccess, {from: $stateParams.from, params: $stateParams.params});
      }
    }, function () {
      $scope.formOption.error = "网络故障，请稍候再试！";
    });
  };

  $scope.forgetPwd = function(){
    //TODO: 功能暂未实现;
  };
})
.controller('MessageCtrl', function($scope, $state, $rootScope){
  $scope.tabs = [{
    name: "alarm",
    icon: "fa fa-bell-o",
    title: "系统通知",
    number: 6,
    style:'list',
    list:[{
      title: '通知111',
      content: '通知111....',
      id:1,
      active: true
    },{
      title: '通知222',
      content: '通知22222....',
      id:2
    },{
      title: '通知3333',
      content: '通知33333....',
      id:3
    }]
  },{
    name: "message",
    icon: "fa fa-comments-o",
    title: "社区消息",
    number: 2,
    content:"社区消息...",
    style:'literal'
  },{
    name: "announce",
    icon: "fa fa-bullhorn",
    title: "系统公告",
    number: 1,
    content:"系统公告...",
    style:'literal'
  }];

  $scope.removeMsg = function(array, index){
    if(array && array.length){
      array.splice(index, 1);
    }
  };

  $scope.showTab = function(item){
    item.active = !item.active;
  };

  $scope.clearMsg = function(array){
    if(array && array.length){
      array.splice(0, array.length);
    }
  };

  $rootScope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $state.go('index');
  };
})
.controller('UserGroupListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, $rootScope, UserGroupService) {
  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true,
    showMenu:false
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 
    $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
      if (sortColumns.length === 0) {
        paginationOptions.sort = null;
      }else{
        paginationOptions.sort = sortColumns[0].sort.direction;
      }
      getPage();
    });

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'groupName',
      displayName: '用户组名'
    },{
      field: 'desc',
      displayName: '描述'
    },{
      field: 'createAt',
      displayName: '创建时间'
    },{
      name: 'groupId',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/user/group/edit/{{COL_FIELD}}">修改</a>&nbsp;&nbsp;<a class="btn-small" href="#/user/group/assign/{{row.entity.groupId}}">分配用户</a>',
      enableFiltering: false
    }
  ];

  $scope.userGroup = {};

  //分页查询
  var getPage = function() {
    var form = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      groupName: $scope.userGroup.groupName || ''
      // startDate: $('#beginCreateTime').val(),
      // endDate: $('#endCreateTime').val()
    };
    UserGroupService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var groups = data.groups || [];
      angular.forEach(groups, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm");
      });
      $scope.gridOptions.data = groups;
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.groupId;
        UserGroupService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.controller('AddUserGroupCtrl', function($scope, $state, UserGroupService, $rootScope, $timeout){
  $scope.UserGroupForm = {
    title:"新增用户组"
  };

  $scope.userGroup = {};

  $scope.submitForm = function(){
    var form = {
      groupName: $scope.userGroup.groupName,
      desc : $scope.userGroup.desc,
      userName: $scope.currentUser.userName
    };
    UserGroupService.create({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditUserGroupCtrl', function($scope, $state, UserGroupService, $rootScope, UserGroup, $timeout){
  $scope.UserGroupForm = {
    title:"更新用户组"
  };

  $scope.userGroup = UserGroup || {};
  var watcher = $scope.$watch("groupName", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.userGroup = UserGroup;
    }, 50);
  });

  $scope.submitForm = function(){
    var form = {
      groupName: $scope.userGroup.groupName,
      desc: $scope.userGroup.desc,
      userName: $scope.currentUser.userName
    };
    UserGroupService.update({id:$state.params.id}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('AssignUserGroupCtrl', function($scope, $state, UserGroupService, $rootScope, UserGroup, $timeout, UserService){
  $scope.UserGroupForm = {
    title:"用户组分配用户"
  };

  $scope.userGroup = UserGroup || {};
  $scope.left = {
    title: '用户列表',
    items:[]
  };
  $scope.right = {
    title: '已选成员',
    items:[]
  };

  var watcher = $scope.$watch("userGroup", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.userGroup = UserGroup;

      var rightItems = [];
      var uniqueItems = [];
      angular.forEach($scope.userGroup.users, function(item){
        rightItems.push({text: item.userName || Base64.decode(item.nickName) + '(微信用户)', value: item.userId});
        uniqueItems.push(item.userId);
      });
      $scope.right.items = rightItems;

      var userList = UserService.getList({currentPage:1, pageSize: 500, model: 0}, function(data){
        var items = data.users || [];
        var leftItems = [];
        angular.forEach(items, function(item){
          if (item.userName || item.nickName) {
            if($.inArray(item.userId, uniqueItems)<0){
              leftItems.push({text: item.userName || item.nickName + '(微信用户)', value: item.userId});
            }
          }
        });
        $scope.left.items = leftItems;
      });

    }, 50);
  });

  $scope.submitForm = function(){
    var selectedUsers = $("select[name='rightItem']>option").map(function(){ 
      return $(this).val(); }
    ).get().join(',');

    var form = {
      groupId: $state.params.id,
      userIds: selectedUsers
    };
    UserGroupService.assign({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})

.controller('UserRoleListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, $rootScope, UserRoleService) {
  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true,
    showMenu:false
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 
    $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
      if (sortColumns.length === 0) {
        paginationOptions.sort = null;
      }else{
        paginationOptions.sort = sortColumns[0].sort.direction;
      }
      getPage();
    });

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'roleName',
      displayName: '角色名'
    },{
      field: 'status',
      displayName: '状态'  
    }, {
      field: 'desc',
      displayName: '描述'  
    },{
      field: 'createAt',
      displayName: '创建时间'
    },{
      name: 'roleId',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/user/role/edit/{{COL_FIELD}}">修改</a>&nbsp;&nbsp;<a class="btn-small" href="#/user/role/assign/{{row.entity.roleId}}">分配用户组</a>&nbsp;&nbsp;<a class="btn-small" href="#/user/role/grant/{{row.entity.roleId}}">角色授权</a>',
      enableFiltering: false
    }
  ];

  $scope.userRole = {};

  //分页查询
  var getPage = function() {
    var form = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      roleName: $scope.userRole.roleName || ''
      // ,startDate: $('#beginCreateTime').val(),
      // endDate: $('#endCreateTime').val()
    };
    UserRoleService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var roles = data.roles || [];
      angular.forEach(roles, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm");
      });
      $scope.gridOptions.data = roles;
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.roleId;
        UserRoleService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.controller('AddUserRoleCtrl', function($scope, $state, UserRoleService, $rootScope, $timeout){
  $scope.UserRoleForm = {
    title:"新增角色"
  };

  $scope.userRole = {};

  $scope.submitForm = function(){
    var form = {
      roleName: $scope.userRole.roleName,
      desc : $scope.userRole.desc,
      userName: $scope.currentUser.userName
    };
    UserRoleService.create({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditUserRoleCtrl', function($scope, $state, UserRoleService, $rootScope, $timeout, UserRole){
  $scope.UserRoleForm = {
    title:"更新角色"
  };

  $scope.userRole = UserRole || {};
  var watcher = $scope.$watch("roleName", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.userRole = UserRole || {};
    }, 50);
  });

  $scope.submitForm = function(){
    var form = {
      roleName: $scope.userRole.roleName,
      desc: $scope.userRole.desc,
      userName: $scope.currentUser.userName
    };
    UserRoleService.update({id: $state.params.id}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('AssignUserRoleCtrl', function($scope, $state, UserRoleService, $rootScope, UserRole, $timeout, UserGroupService){
  $scope.UserRoleForm = {
    title:"角色分配用户组"
  };

  $scope.userRole = UserRole || {};
  $scope.left = {
    title: '用户组列表',
    items:[]
  };
  $scope.right = {
    title: '已选用户组',
    items:[]
  };

  var watcher = $scope.$watch("roleName", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.userRole = UserRole;

      var rightItems = [];
      var uniqueItems = [];
      angular.forEach($scope.userRole.groups, function(item){
        rightItems.push({text: item.groupName, value: item.groupId});
        uniqueItems.push(item.groupId);
      });
      $scope.right.items = rightItems;

      UserGroupService.getList({currentPage:1, pageSize: 5000}, function(data){
        var items = data.groups || [];
        var leftItems = [];
        angular.forEach(items, function(item){
          if($.inArray(item.groupId, uniqueItems)<0){
            leftItems.push({text: item.groupName, value: item.groupId});
          }
        });
        $scope.left.items = leftItems;
      });

    }, 50);
  });

  $scope.submitForm = function(){
    var selectedIds = $("select[name='rightItem']>option").map(function(){ 
      return $(this).val(); }
    ).get().join(',');

    var form = {
      roleId: $state.params.id,
      groupIds: selectedIds
    };
    UserRoleService.assignGroups({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('GrantUserRoleCtrl', function($scope, $state, UserRoleService, $rootScope, UserRole, $timeout, PermissionService){
  $scope.UserRoleForm = {
    title:"角色授权"
  };

  $scope.userRole = UserRole || {};

  var watcher = $scope.$watch("roleName", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.userRole = UserRole || {};
    }, 50);
  });

  PermissionService.getChildren({id: 0}, function(data){
    if(data && data.length){
      UserRoleService.getPriviledge({}, {roleId: $state.params.id}, function(pData){
        if(pData && pData.length){
          for(var i=0; i<data.length; i++){
            for(var j=0; j<pData.length; j++){
              if(data[i].permitId === pData[j].permitId){
                data[i].$$isChecked = true;
              }
            }
          }
        }
        var permits = iterator(data, 0);
        $scope.priviledges = permits;
      });
    }
  });

  function iterator(data, pid) {
    var result = [], temp;
    for (var i = 0; i < data.length; i++) {
      if (data[i].parentPermitId == pid) {
        var obj = data[i];
        temp = iterator(data, data[i].permitId);
        if (temp.length > 0) {
          obj.children = temp;
        }
        result.push(obj);
      }
    }
    return result;
  }

  $scope.selectNode = function(item){
    var children = item.children;
    if(children && children.length){
      for(var i=0; i<children.length; i++){
        var child = children[i];
        child.$$isChecked = item.$$isChecked;
        $scope.selectNode(child);
      }
    } else {
      // 叶子节点，反选父节点
      if (item.$$isChecked) {
        $scope.priviledges && $scope.priviledges[0] && $scope.priviledges[0].children.forEach(p => {
          if (p.permitId == item.parentPermitId) {
            p.$$isChecked = true;
          }
        });
      }
    }
  };

  $scope.submitForm = function(){
    var permitIds = $("input[name='permission']:checked").map(function(){ return $(this).data("id"); }).get().join(',');

    var form = {
      roleId: $state.params.id,
      permitIds: permitIds
    };

    UserRoleService.assignPermits({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('ResourcesListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, $rootScope, ResoucesService, PermissionService) {
  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true,
    showMenu:false
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 
    $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
      if (sortColumns.length === 0) {
        paginationOptions.sort = null;
      }else{
        paginationOptions.sort = sortColumns[0].sort.direction;
      }
      getPage();
    });

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'resourceName',
      displayName: '资源名称'
    },{
      field: 'resourceURI',
      displayName: '资源URI',
      width: 350
    },{
      field: 'desc',
      displayName: '描述'
    },{
      field: 'status',
      displayName: '状态',
      width: 80
    },{
      field: 'sort',
      displayName: '排序',
      width: 80
    },{
      name: 'resourceId',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/user/resources/{{row.entity.permitId}}/edit/{{COL_FIELD}}">修改</a>',
      enableFiltering: false
    }
  ];

  $scope.resources = {};
  $scope.ResourceForm = {
    title: '查看资源'
  };

  $scope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $rootScope.nestedAnimated = true;
    $state.go('permissions', {id: $state.params.id});
    // $rootScope.$window.history.back();
  };

  //分页查询
  var getPage = function() {
    // var form = {
    //   currentPage:paginationOptions.pageNumber, 
    //   pageSize:paginationOptions.pageSize, 
    //   resourceName: $scope.resources.resourceName || ''
    //   // ,startDate: $('#beginCreateTime').val(),
    //   // endDate: $('#endCreateTime').val()
    // };
    PermissionService.getResources({id: $state.params.id}, function(data){
      $scope.gridOptions.totalItems = data.length || 0;
      // var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      $scope.gridOptions.data = data || [];
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if($rootScope.nestedAnimated){
      $rootScope.nestedAnimated = false;
      $rootScope.currentAnimated = false;
    }else if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.resourceId;
        ResoucesService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.controller('AddResourceCtrl', function($scope, $state, ResoucesService, $rootScope, $timeout){
  $scope.ResourcesForm = {
    title:"新增资源"
  };

  $scope.resources = {
    resourceTypes:[{
      id: 1, name: "", desc: "功能点"
    },{
      id: 2, name: "grid", desc: "多级菜单"
    }]
  };

  $scope.submitForm = function(){
    var form = {
      resourceName: $scope.resources.resourceName,
      resourceType: $scope.resources.resourceType,
      resourceURI: $scope.resources.resourceURI,
      desc : $scope.resources.desc,
      sort: $scope.resources.sort,
      permitId: $state.params.id
    };
    ResoucesService.create({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditResourceCtrl', function($scope, $state, ResoucesService, $rootScope, $timeout, Resource){
  $scope.ResourcesForm = {
    title:"更新资源"
  };

  $scope.resources = Resource || {};
  $scope.resources.resourceTypes = [{
    id: 1, name: "", desc: "功能点"
  },{
    id: 2, name: "grid", desc: "多级菜单"
  }];

  var watcher = $scope.$watch("resourceName", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.resources = Resource || {};
      $scope.resources.resourceType = "1";
    }, 50);
  });

  $scope.submitForm = function(){
    var form = {
      resourceName: $scope.resources.resourceName,
      resourceType: $scope.resources.resourceType,
      resourceURI: $scope.resources.resourceURI,
      desc : $scope.resources.desc,
      sort: $scope.resources.sort
    };
    ResoucesService.update({id: $state.params.id}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^', {id: $scope.resources.permitId});
    });
  };
  
  $rootScope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $state.go('^', {id: $scope.resources.permitId});
  };
})
.controller('DataDictListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, $rootScope, DataDictService) {
  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true,
    showMenu:false
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 
    $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
      if (sortColumns.length === 0) {
        paginationOptions.sort = null;
      }else{
        paginationOptions.sort = sortColumns[0].sort.direction;
      }
      getPage();
    });

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'propertyName',
      displayName: '配置名称',
      cellTemplate: '<a class="btn-small" href="#/datadict/{{row.entity.id}}">{{COL_FIELD}}</a>',
      width: 120
    },{
      field: 'value',
      displayName: '配置值',
      width: 200
    },{
      field: 'status',
      displayName: '状态',
      width: 80
    },{
      field: 'sort',
      displayName: '排序',
      width: 80
    },{
      field: 'parentId',
      displayName: '父级ID'
    },{
      field: 'parentPath',
      displayName: '父级路径'
    },{
      field: 'css',
      displayName: '样式名',
      width: 80
    },{
      field: 'desc',
      displayName: '描述',
      width: 120
    },{
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/datadict/{{row.entity.parentId}}/edit/{{COL_FIELD}}">修改</a>&nbsp;&nbsp;<a class="btn-small" href="#/datadict/{{row.entity.parentId}}/children/{{COL_FIELD}}">增加子级配置</a>',
      enableFiltering: false,
      width: 180
    }
  ];

  $scope.dict = {
    statusList: [{
      id: 0,
      name: '可用'
    },{
      id: 1,
      name: '冻结'
    }]
  };

  var breadcrumbs = $rootScope.dictBreadcrumbs || [];
  var parentId = $scope.parentId = $state.params.id;
  
  if(!parentId){
    breadcrumbs = [];
    breadcrumbs.push({id: parentId, text: '根目录'});
  }else{
    DataDictService.getParents({id: $state.params.id }, function(data){
      breadcrumbs = [];
      breadcrumbs.push({id: parentId, link: '#/datadict/', text: '根目录'});
      for(var i=data.length-1; i>=0; i--){
        var item = data[i];
        breadcrumbs.push({id: item.id, link: '#/datadict/'+item.id, text: item.propertyName});
      }
      $rootScope.dictBreadcrumbs = breadcrumbs;
    });
  }
  $rootScope.dictBreadcrumbs = breadcrumbs;

  //分页查询
  var getPage = function() {
    var form = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      propertyName: $scope.dict.key || '',
      status: $scope.dict.status || 0,
      startDate: $('#beginCreateTime').val(),
      endDate: $('#endCreateTime').val(),
      parentId: $state.params.id || ''
    };
    DataDictService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      $scope.gridOptions.data = data.dataDics || [];
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
  });

  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;
        DataDictService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.controller('AddDataDictCtrl', function($scope, $state, DataDictService, $rootScope, $timeout){
  $scope.DictForm = {
    title:"新增数据字典"
  };

  $scope.submitForm = function(){
    var form = {
      propertyName: $scope.dict.key,
      value: $scope.dict.value,
      desc : $scope.dict.desc,
      css : $scope.dict.css || '',
      parentId: $state.params.id || '',
      sort: $scope.dict.sort,
      status: $scope.dict.status || 0
    };
    DataDictService.create({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditDataDictCtrl', function($scope, $state, DataDictService, $rootScope, $timeout, DataDict){
  $scope.DictForm = {
    title:"更新数据字典"
  };
  $scope.dict = DataDict || {};

  var watcher = $scope.$watch("propertyName", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.dict = DataDict || {};
    }, 50);
  });
  $scope.submitForm = function(){
    var form = {
      propertyName: $scope.dict.propertyName,
      value: $scope.dict.value,
      desc : $scope.dict.desc,
      css : $scope.dict.css || '',
      parentId: $scope.dict.parentId,
      parentPath: $scope.dict.parentPath,
      sort: $scope.dict.sort,
      status: $scope.dict.status
    };
    DataDictService.update({id: $state.params.id}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^', {id: $scope.dict.parentId || ''});
    });
  };


  $rootScope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $state.go('^', {id: $scope.dict.parentId || ''});
  };

})
.controller('AddDataDictChildCtrl', function($scope, $state, DataDictService, $rootScope, $timeout, DataDict){
  $scope.DictForm = {
    title:"添加子级配置项"
  };
  $scope.dict = {};
  $scope.parentDict = DataDict || {};

  var watcher = $scope.$watch("propertyName", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.parentDict = DataDict || {};
    }, 50);
  });
  $scope.submitForm = function(){
    var form = {
      propertyName: $scope.dict.key,
      value: $scope.dict.value,
      css : $scope.dict.css || '',
      desc : $scope.dict.desc,
      parentId: $state.params.dictId,
      sort: $scope.dict.sort
    };
    DataDictService.create({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('PermissionListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, $rootScope, PermissionService) {
  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true,
    showMenu:false
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 
    $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
      if (sortColumns.length === 0) {
        paginationOptions.sort = null;
      }else{
        paginationOptions.sort = sortColumns[0].sort.direction;
      }
      getPage();
    });

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'permitName',
      displayName: '权限名称',
      cellTemplate:'<a class="btn-small" href="#/user/permissions/{{row.entity.permitId}}?permitName={{row.entity.permitName}}">{{COL_FIELD}}</a>',
      width:250
    },{
      field: 'desc',
      displayName: '链接'
    },{
      field: 'operationType',
      displayName: '样式',
      width:80
    },{
      field: 'status',
      displayName: '状态',
      width:80
    },{
      field: 'parentPermitId',
      displayName: '父级ID',
      width:80
    },{
      name: 'permitId',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/user/permissions/{{row.entity.parentPermitId}}/edit/{{COL_FIELD}}">修改</a>&nbsp;&nbsp;<a class="btn-small" href="#/user/resources/{{row.entity.permitId}}">查看资源</a>&nbsp;&nbsp;<a class="btn-small" href="#/user/resources/{{row.entity.permitId}}/add">新增资源</a>&nbsp;&nbsp;<a class="btn-small" href="#/user/permissions/{{row.entity.parentPermitId}}/children/{{row.entity.permitId}}">增加子级权限</a>',
      enableFiltering: false
    }
  ];

  $scope.permissions = {};

  var breadcrumbs = $rootScope.breadcrumbs || [];
  var parentId = $scope.parentId = $state.params.id;
  var pos = -1;
  for(var i=0; i<breadcrumbs.length; i++){
    var item = breadcrumbs[i];
    if(item.id == parentId){
      pos = i;
    }
  }
  if(parentId>=0 && pos < 0){
    if(!parentId || parentId==="0"){
      breadcrumbs = [];
      breadcrumbs.push({id: parentId, text: '根目录'});
    }else{
      PermissionService.getParentPermits({id: $stateParams.id }, function(data){
        breadcrumbs = [];
        breadcrumbs.push({id: parentId, link: '#/user/permissions/', text: '根目录'});
        for(var i=data.length-1; i>=0; i--){
          var item = data[i];
          breadcrumbs.push({id: item.permitId, link: '#/user/permissions/'+item.permitId, text: item.permitName});
        }
        $rootScope.breadcrumbs = breadcrumbs;
      });
    }
    // var permitName = $rootScope.$location.search().permitName || name;
    // breadcrumbs.push({id: parentId, link: '#/user/permissions/'+parentId, text: permitName});
  }else if(pos >= 0){
    breadcrumbs.splice(pos+1, breadcrumbs.length-1-pos);
  }
  $rootScope.breadcrumbs = breadcrumbs;

  //分页查询
  var getPage = function() {
    var form = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      permitName: $scope.permissions.permitName || '',
      startDate: $('#beginCreateTime').val(),
      endDate: $('#endCreateTime').val(),
      permitId: $stateParams.id || 0
    };
    PermissionService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      $scope.gridOptions.data = data.priviledges || [];
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.permitId;
        PermissionService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.controller('AddPermissionCtrl', function($scope, $state, PermissionService, $rootScope, $timeout){
  $scope.PermissionForm = {
    title:"新增权限"
  };

  $scope.permission = {
    operationTypes:[{
      id: 1, name: "级联菜单"
    },{
      id: 2, name: "功能点"
    }],
    operationType: 1
  };

  $scope.submitForm = function(){
    var form = {
      permitName: $scope.permission.permitName,
      operationType: $scope.permission.operationType,
      desc : $scope.permission.desc,
      parentPermitId: $state.params.id || 0
    };
    PermissionService.create({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^', {id: $state.params.id});
    });
  };
})
.controller('EditPermissionCtrl', function($scope, $state, PermissionService, $rootScope, $timeout, Priviledge){
  $scope.PermissionForm = {
    title:"更新权限"
  };

  $scope.permission = Priviledge || {};
  $scope.permission.operationTypes = [{
    id: 1, name: "级联菜单"
  },{
    id: 2, name: "功能点"
  }];

  var watcher = $scope.$watch("permitName", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.permission = Priviledge || {};
      $scope.permission.operationType = Priviledge.operationType + '' || '2';
    }, 50);
  });

  $scope.submitForm = function(){
    var form = {
      permitName: $scope.permission.permitName,
      operationType: $scope.permission.operationType,
      desc : $scope.permission.desc
    };

    PermissionService.update({id: $state.params.permitId}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('permissions', {id: $state.params.id});
    });
  };
})
.controller('AddChildPermissionCtrl', function($scope, $state, PermissionService, $rootScope, $timeout, Priviledge){
  $scope.PermissionForm = {
    title:"添加子级权限"
  };

  $scope.permission = Priviledge || {};
  $scope.permission.operationTypes = [{
    id: 1, name: "查询"
  },{
    id: 2, name: "更新"
  }];

  var watcher = $scope.$watch("permitName", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.permission = Priviledge || {};
      $scope.permission.operationType = "2";
    }, 50);
  });

  $scope.submitForm = function(){
    var form = {
      permitName: $scope.permission.childPermitName,
      operationType: $scope.permission.operationType,
      desc : $scope.permission.desc,
      parentPermitId: $state.params.permitId
    };

    PermissionService.create({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('permissions', {id: $state.params.id});
    });
  };
})

.controller('TagListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, TagService, $rootScope) {
  $scope.tag = {};
  $scope.TagForm = {
    title:'标签管理'
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    enableSorting: true,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'name',
      displayName: '标签名称',
      width:280
    },{
      field: 'weight',
      displayName: '标签权重',
      width:120
    },{
      field: 'user.name',
      displayName: '用户名',
      width:300
    }, {
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/tag/edit/{{COL_FIELD}}">修改</a>',
      enableFiltering: false
    }
  ];

  //分页查询
  var getPage = function() {
    var userName = $scope.tag.userName || $scope.currentUser.userName;
    var tagName = $scope.tag.name || '';

    TagService.getList({ userName: userName }, function(data){
      var tagData = data || [];
      var filteredData = [];
      angular.forEach(tagData, function(item){
        if(tagName && item.name.indexOf(tagName) != -1){
          filteredData.push(item);
        }
      });

      $scope.gridOptions.data = tagName ? filteredData: tagData;
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){

    if($rootScope.nestedAnimated){
      $rootScope.nestedAnimated = false;
      $rootScope.currentAnimated = false;
    }else if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;
 
        TagService.remove({
          id:id
        }, function(){
          getPage();
        });
      });

      $scope.$emit("updateTag");
    }
    $('#myModal').modal('hide');
  }; 

})
.controller('AddTagCtrl', function($scope, $state, $timeout, TagService, $rootScope){
  $scope.TagForm = {
    title:"新增标签"
  };

  $scope.tag = {
    weight: 1
  };

  $scope.submitForm = function(){
    var form = {
      name: $scope.tag.name,
      weight: $scope.tag.weight,
      user: {
        id: $scope.currentUser.userId,
        name: $scope.currentUser.userName
      }
    };

    TagService.create({}, form, function(data){
      $scope.$emit("updateTag");
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditTagCtrl', function($scope, $state, $timeout, TagService, $rootScope, Tag){
  $scope.TagForm = {
    title:"更新标签"
  };

  $scope.tag = {};

  var watcher = $scope.$watch("tag", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        $scope.tag.name = Tag.name;
      }, 50);
    }

  });

  $scope.submitForm = function(){
    var form = {
      id:$state.params.id,
      name: $scope.tag.name,
      weight: $scope.tag.weight,
      user: {
        id: $scope.currentUser.userId,
        name: $scope.currentUser.userName
      }
    };

    TagService.update({}, form, function(data){
      $scope.$emit("updateTag");
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('ChannelListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, ChannelService, $rootScope) {
  $scope.channel = {};
  $scope.Form = {
    title:'栏目管理'
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    enableSorting: true,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'title',
      displayName: '栏目名称',
      width:280
    },{
      field: 'pageSize',
      displayName: '显示记录数',
      width:100
    },{
      field: 'sort',
      displayName: '排序值',
      width:80
    },{
      field: 'description',
      displayName: '栏目描述'
    },{
      field: 'createAt',
      displayName: '创建时间',
      width:210
    },{
      field: 'createBy',
      displayName: '创建者',
      width:120
    }, {
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/channel/edit/{{COL_FIELD}}">修改</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="btn-small" href="#/channel/{{row.entity.id}}/goods">栏目商品管理</a>',
      enableFiltering: false
    }
  ];

  //分页查询
  var getPage = function() {
    var title = $scope.channel.title || '';
    ChannelService.getList({ title:  title}, function(res){
      var channels = res.data || [];
      angular.forEach(channels, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm:ss");
      });
      $scope.gridOptions.data = channels;
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if($rootScope.nestedAnimated){
      $rootScope.nestedAnimated = false;
      $rootScope.currentAnimated = false;
    }else if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;
 
        ChannelService.remove({
          id:id
        }, function(){
          getPage();
        });
      });

    }
    $('#myModal').modal('hide');
  }; 

})
.controller('AddChannelCtrl', function($scope, $state, $timeout, ChannelService, $rootScope){
  $scope.Form = {
    title:"新增栏目"
  };

  $scope.channel = {
    pageSize: 8
  };

  $scope.submitForm = function(){
    var form = {
      title: $scope.channel.title,
      pageSize: $scope.channel.pageSize,
      description: $scope.channel.description,
      createBy: $scope.currentUser.userName,
      sort: $scope.channel.sort || 0
    };

    ChannelService.create({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditChannelCtrl', function($scope, $state, $timeout, ChannelService, $rootScope,  Channel){
  $scope.Form = {
    title:"更新栏目"
  };

  $scope.channel = {};

  var watcher = $scope.$watch("channel", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        $scope.channel = Channel && Channel.data || {};
      }, 50);
    }

  });

  $scope.submitForm = function(){
    var form = {
      id:$state.params.id,
      title: $scope.channel.title,
      pageSize: $scope.channel.pageSize,
      description: $scope.channel.description,
      createBy: $scope.currentUser.userName,
      sort: $scope.channel.sort || 0
    };

    ChannelService.update({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('ChannelGoodsListCtrl', function($scope, $state, uiGridConstants, myModal,ChannelGoodsService, $rootScope){
  $scope.channelGoods = {};

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };

  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });

    init();
  };
   
  $scope.gridOptions.columnDefs = [{
      field: 'name',
      displayName: '商品名称'
    },{
      field: 'price',
      displayName: '价格',
      cellTemplate: '<span>¥{{row.entity.price}}</span>'
    },{
      name: 'salesCount',
      displayName: '已售',
      cellTemplate: '<span>{{row.entity.stock.salesCount}}件</span>'
    },{
      name: 'sellPoint',
      displayName: '卖点'
    },{
      name: 'cid',
      displayName: '栏目ID'
    }
  ];

  var getPage = function() {
    var form = {
      name: $scope.channelGoods.name
    };

    ChannelGoodsService.getList({
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize,
      cid: $state.params.id || ""
    }, form, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      $scope.gridOptions.data = data.data || [];
    });
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if($rootScope.nestedAnimated){
      $rootScope.nestedAnimated = false;
      $rootScope.currentAnimated = false;
    }else if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  $scope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $rootScope.nestedAnimated = true;
    $state.go('^');
  };

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        ChannelGoodsService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };

})
.controller('AddChannelGoodsCtrl', function($scope, $state, $timeout, ChannelGoodsService, $rootScope, Cid){
  $scope.Form = {
    title:"新增栏目商品"
  };
  $rootScope.multiple = true;
  $scope.channelGoods = {};

  $timeout(function(){
    $scope.channelGoods.cid = Cid || "";
  }, 500);

  $scope.removeProduct = function(idx) {
    if ($rootScope.selectedProducts && $rootScope.selectedProducts.length > idx) {
      $rootScope.selectedProducts.splice(idx, 1);
    }
  };
  $scope.cleanProducts = function() {
    $rootScope.selectedProducts = [];
    $rootScope.multiSelectProducts = [];
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $rootScope.multiple = false;
    $rootScope.multiSelectProducts = [];
    $rootScope.selectedProducts = [];
  });

  $scope.submitForm = function(){
    var cid = $scope.channelGoods.cid;
    var goods = $rootScope.selectedProducts;
    var batchGoods = [];
    if (goods && goods.length) {
      goods.forEach(function(item) {
        item.cid = cid;
        batchGoods.push({
          cid: cid,
          name: item.name,
          price: item.price,
          sellPoint: item.sellPoint,
          collected: item.collected,
          pictures: item.pictures,
          stock: item.stock,
          artworkId: item.id
        });
      });
    }
    var form = {
      goodsList: batchGoods
    };
    ChannelGoodsService.batchInsert({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
});

/**
 * 文章模块列表
 * @type {[type]}
 */
var articleListModule = angular.module("ArticleListModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ngFileUpload']); 
articleListModule.controller('ArticleListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, Categories, ArticleService, $rootScope) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'icon',
      displayName: '文章图标',
      width:80,
      cellTemplate: '<a href="javascript:void(0)" title="标题：{{row.entity.title}}&#10;作者：{{row.entity.author}}&#10;标签：{{row.entity.tags}}"><img ng-if="COL_FIELD" ng-src="{{COL_FIELD}}" class="article-icon"><img ng-if="!COL_FIELD" src="images/defaultIcon.jpg" class="article-icon"></a>'
    },{
      field: 'title',
      displayName: '文章标题',
      width:280
    },{
      field: 'categoryName',
      displayName: '文章分类',
      width:120
    },{
      field: 'author',
      displayName: '作者',
      width:120
    }, {
      field: 'postTime',
      displayName: '发布时间',      
      type: 'date',
      width:140
    }, {
      field: 'status',
      displayName: '状态',
      width:80,
      cellFilter:'mapStatus'
    }, {
      field: 'public',
      displayName: '是否公开',
      width:100
    }, {
      field: 'recommned',
      displayName: '推荐',
      width:80
    }, {
      field: 'top',
      displayName: '置顶',
      width:80
    }, {
      field: 'pv',
      displayName: 'PV',
      width:80
    }, {
      field: 'sort',
      displayName: '排序',
      width:80
    }, {
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/article/edit/{{COL_FIELD}}?type=1">修改</a>&nbsp;&nbsp;<a class="btn-small" href="#/article/view/{{row.entity.id}}">预览</a>',
      enableFiltering: false
    }
  ];

  $scope.article = {
    statusList:[{
      id:1,
      name:'已发布'
    },{
      id:2,
      name:'草稿'
    }],
    type: $state.params.type || 1
  };
  $scope.article.categoryList = Categories.categories || [];

  //分页查询
  var getPage = function() {
    var articleForm = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      categoryId:$scope.article.category||'',
      status:$scope.article.status||0,
      tags:$scope.article.tags,
      title:$scope.article.title,
      startDate:$("#beginPublishTime").val(),
      endDate:$("#endPublishTime").val(),
      type: 1
    };
    ArticleService.getList(articleForm, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var articleData = data.articles || [];

      angular.forEach(articleData, function(item){
        if (item.wxSharePic) {
          item.icon = Yihu.util.setContext($scope.downloadUrl, item.wxSharePic) + '?w=80&h=80';
        }
      });
      $scope.gridOptions.data = articleData;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        ArticleService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
articleListModule.controller('MyArticleListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, Categories, ArticleService, $rootScope) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'icon',
      displayName: '文章图标',
      width:80,
      cellTemplate: '<a href="javascript:void(0)" title="标题：{{row.entity.title}}&#10;作者：{{row.entity.author}}&#10;标签：{{row.entity.tags}}"><img ng-if="COL_FIELD" ng-src="{{COL_FIELD}}" class="article-icon"><img ng-if="!COL_FIELD" src="images/defaultIcon.jpg" class="article-icon"></a>'
    },{
      field: 'title',
      displayName: '文章标题',
      width:280
    },{
      field: 'categoryName',
      displayName: '文章分类',
      width:120
    },{
      field: 'author',
      displayName: '作者',
      width:120
    }, {
      field: 'postTime',
      displayName: '发布时间',      
      type: 'date',
      width:140
    }, {
      field: 'status',
      displayName: '状态',
      width:80,
      cellFilter:'mapStatus'
    }, {
      field: 'public',
      displayName: '是否公开',
      width:100
    }, {
      field: 'recommned',
      displayName: '推荐',
      width:80
    }, {
      field: 'top',
      displayName: '置顶',
      width:80
    }, {
      field: 'pv',
      displayName: 'PV',
      width:80
    }, {
      field: 'sort',
      displayName: '排序',
      width:80
    }, {
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/article/edit/{{COL_FIELD}}?type=2">修改</a>&nbsp;&nbsp;<a class="btn-small" href="#/article/view/{{row.entity.id}}">预览</a>',
      enableFiltering: false
    }
  ];

  $scope.article = {
    statusList:[{
      id:1,
      name:'已发布'
    },{
      id:2,
      name:'草稿'
    }],
    type: $state.params.type || 1
  };
  $scope.article.categoryList = Categories.categories || [];

  //分页查询
  var getPage = function() {
    var articleForm = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      categoryId:$scope.article.category||'',
      status:$scope.article.status||0,
      tags:$scope.article.tags,
      title:$scope.article.title,
      startDate:$("#beginPublishTime").val(),
      endDate:$("#endPublishTime").val(),
      type: 2,
      createUserId: $scope.currentUser.userId || 0
    };
    ArticleService.getList(articleForm, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var articleData = data.articles || [];

      angular.forEach(articleData, function(item){
        if (item.wxSharePic) {
          item.icon = Yihu.util.setContext($scope.downloadUrl, item.wxSharePic) + '?w=80&h=80';
        }
      });
      $scope.gridOptions.data = articleData;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        ArticleService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
articleListModule.controller('FaqArticleListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, Categories, ArticleService, $rootScope) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'icon',
      displayName: '文章图标',
      width:80,
      cellTemplate: '<a href="javascript:void(0)" title="标题：{{row.entity.title}}&#10;作者：{{row.entity.author}}&#10;标签：{{row.entity.tags}}"><img ng-if="COL_FIELD" ng-src="{{COL_FIELD}}" class="article-icon"><img ng-if="!COL_FIELD" src="images/defaultIcon.jpg" class="article-icon"></a>'
    },{
      field: 'title',
      displayName: '文章标题',
      width:280
    },{
      field: 'categoryName',
      displayName: '文章分类',
      width:120
    },{
      field: 'author',
      displayName: '作者',
      width:120
    }, {
      field: 'postTime',
      displayName: '发布时间',      
      type: 'date',
      width:140
    }, {
      field: 'status',
      displayName: '状态',
      width:80,
      cellFilter:'mapStatus'
    }, {
      field: 'public',
      displayName: '是否公开',
      width:100
    }, {
      field: 'recommned',
      displayName: '推荐',
      width:80
    }, {
      field: 'top',
      displayName: '置顶',
      width:80
    }, {
      field: 'pv',
      displayName: 'PV',
      width:80
    }, {
      field: 'sort',
      displayName: '排序',
      width:80
    }, {
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/article/view/{{row.entity.id}}">预览</a>',
      enableFiltering: false
    }
  ];

  $scope.article = {};

  //分页查询
  var getPage = function() {
    var articleForm = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      categoryId:$scope.article.category||'',
      status:$scope.article.status||0,
      tags: '系统示范文章',
      title:$scope.article.title,
      startDate:$("#beginPublishTime").val(),
      endDate:$("#endPublishTime").val(),
      type: 2
    };
    ArticleService.getList(articleForm, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var articleData = data.articles || [];

      angular.forEach(articleData, function(item){
        if (item.wxSharePic) {
          item.icon = Yihu.util.setContext($scope.downloadUrl, item.wxSharePic) + '?w=80&h=80';
        }
      });
      $scope.gridOptions.data = articleData;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        ArticleService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.filter('mapStatus', function(){
  var statusHash = {
    1:'已发布',
    2:'草稿'
  };
  return function(input){
    return statusHash[input];
  };
})
.controller('AddArticleCtrl', function($scope, $state, $timeout, Categories, ArticleService, Upload, $rootScope, Unsaved,myModal, FileManagerService, DataDictService){
  $scope.ArticleForm = {
    title:"新增文章"
  };
  
  $scope.article = {
    isPublic:'true',
    layout: 'big',
    source: '&nbsp;'
  };
  $scope.videos = [{type: '', url: ''}];
  $scope.selectedTags = "";
  $rootScope.multiple = true;

  var watcher = $scope.$watch("article", function(newVal, oldVal){
    if(newVal){
      watcher();
      init();

      $timeout(function(){
        var cats = Categories.categories;
        $scope.article.categoryList = getCategoryTree(cats);
        $scope.article.id = Unsaved.id;
        $scope.article.content = Unsaved.content;
        $scope.loadVideoTypes();
      }, 50);
    }
  });

  function getCategoryTree(cats) {
    var root = [];
    for(var i=0; i<cats.length; i++) {
      var item = cats[i];
      if (item.parentId == '0') {
        root.push(item);
      }
    }
    for(var j=0; j<cats.length; j++) {
      var node = cats[j];
      if (node.parentId != '0') {
        var idx = getTreeIndex(root, node);
        if (idx >= 0) {
          node.name = '　　|---' + node.name;
          root.splice(idx + 1, 0, node); 
        }
      }
    }
    return root;
  }

  function getTreeIndex(root, node) {
    for (var i=0; i<root.length; i++) {
      if (root[i].id == node.parentId) {
        return i;
      }
    }
    return -1;
  }

  $scope.article.pictures = [];
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.article.title,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.article.pictures.splice(i, 1);
      }
    });
  };
  $scope.loadVideoTypes = function(){
    DataDictService.getChildren({
      parentPath: 'cms/config/videotype'
    }, function(data){
      $scope.videoTypes = data.childrens || [];
    });
  };
  $scope.addVideo = function(){
    $scope.videos.push({type: '', url: ''});
  };
  $scope.removeVideo = function(index) {
    if (index && $scope.videos.length > index) {
      $scope.videos.splice(index, 1);
    }
  };

  // upload on files select or drop
  $scope.upload  = function (files) {
    if(!files){
      return;
    }
    var uploadTotal = $scope.article.layout == 'small' ? 2 : 1;
    if(($scope.article.pictures && $scope.article.pictures.length >= uploadTotal) || (files && files.length > uploadTotal)){
      alert('已超过文件上传阈值，最多上传' + uploadTotal + '个文件!');
      return;
    }

    var uploadTask = $scope.uploadTask = { files: [] };
    if (files && files.length) {
      $scope.showDialog = true;

      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.article.pictures.push({
                id: data.id, 
                width: data.width,
                height: data.height,
                thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
                thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };

  $scope.submitForm = function(){
    if ($scope.videos.length === 1 && $scope.videos[0].url === '') {
      $scope.videos = [];
    }
    var articleForm = {
      title:$scope.article.title,
      subTitle:$scope.article.subTitle,
      categoryId: $scope.article.category,
      categoryName:$("select[name='category']").find("option:selected").text().replace('　　|---', ''),
      author:$scope.article.author,
      content:Yihu.util.replaceLazyHtml($scope.article.contentBody),
      keyword:($scope.selectedTags && $scope.selectedTags.split(" ")) || [],
      summary:$scope.article.summary,
      relates: $rootScope.selectedProducts,
      relateTile: $scope.article.relateTitle,
      videoTitle: $scope.article.videoTitle,
      wxSharePic: $scope.article.wxSharePic,
      public:$("input[name='isPublic']").prop('checked'),
      recommned:$("input[name='isRecommend']").prop('checked'),
      top:$("input[name='isTop']").prop('checked'),
      original:$("input[name='isOriginal']").prop('checked'),
      status: 1,
      icons: $scope.article.pictures,
      sort:$scope.article.sort,
      pv:$scope.article.pv,
      editor: $scope.article.editor,
      inputer: $scope.article.inputer,
      auditor: $scope.article.auditor,
      source:Yihu.util.replaceLazyHtml($scope.article.sourceBody),
      createBy:$scope.currentUser.userId,
      videos: $scope.videos,
      postTime:$("#postTime").val(),
      layout: $scope.article.layout,
      type: $state.params.type || 1
    };

    ArticleService.create({}, articleForm, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      history.back();
    });
  };

  $scope.saveForm = function(){
    if ($scope.videos.length === 1 && $scope.videos[0].url === '') {
      $scope.videos = [];
    }
    var articleForm = {
      title:$scope.article.title,
      subTitle:$scope.article.subTitle,
      categoryId: $scope.article.category,
      categoryName:$("select[name='category']").find("option:selected").text().replace('　　|---', ''),
      author:$scope.article.author,
      content:Yihu.util.replaceLazyHtml($scope.article.contentBody),
      keyword:($scope.selectedTags && $scope.selectedTags.split(" ")) || [],
      summary:$scope.article.summary,
      relates: $rootScope.selectedProducts,
      relateTile: $scope.article.relateTitle,
      videoTitle: $scope.article.videoTitle,
      wxSharePic: $scope.article.wxSharePic,
      public:$("input[name='isPublic']").prop('checked'),
      recommned:$("input[name='isRecommend']").prop('checked'),
      top:$("input[name='isTop']").prop('checked'),
      original:$("input[name='isOriginal']").prop('checked'),
      status: 2,
      icons: $scope.article.pictures,
      sort:$scope.article.sort,
      pv:$scope.article.pv,
      editor: $scope.article.editor,
      inputer: $scope.article.inputer,
      auditor: $scope.article.auditor,
      createBy:$scope.currentUser.userId,
      source:Yihu.util.replaceLazyHtml($scope.article.sourceBody),
      videos: $scope.videos,
      postTime:$("#postTime").val(),
      layout: $scope.article.layout,
      type: $state.params.type || 1
    };
    ArticleService.create({}, articleForm, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      history.back();
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=150"),width: width, height: height});
            $scope.article.pictures.push({ id: id, width: width, height: height, 
              thWidth: { width: box.data("thwidthWidth") || "", height: box.data("thwidthHeight") || ""}, 
              thHeight: { width: box.data("thheightWidth") || "", height: box.data("thheightHeight") || ""} 
            });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order:"name",
      desc:1,
      // type:"image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };
  $scope.removeProduct = function(idx) {
    if ($rootScope.selectedProducts && $rootScope.selectedProducts.length > idx) {
      $rootScope.selectedProducts.splice(idx, 1);
    }
  };
  $scope.cleanProducts = function() {
    $rootScope.selectedProducts = [];
    $rootScope.multiSelectProducts = [];
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.multiple = false;
    $rootScope.multiSelectProducts = [];
    $rootScope.selectedProducts = [];
  });

  $scope.uploadPic = function (file) {
    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      if(data.code===0){
        uploadedCallback(data.fileName, data);
        $timeout(function(){
          $scope.article.wxiconurl = data.url+"?w=80";
          $scope.article.wxSharePic = data.id;
        });
      }
    }, function (resp) {
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progressPercentage + '% ');
    });
  };

  function uploadedCallback(fileName, fileItem){
    var form = {
      path: '/product/默认库', 
      fileName: fileName,
      fileType: guessFileType(fileName),
      picture: {
        width: fileItem.width,
        height: fileItem.height,
        thWidth: { width: fileItem.thWidth && fileItem.thWidth.width, height: fileItem.thWidth && fileItem.thWidth.height},
        thHeight: { width: fileItem.thHeight && fileItem.thHeight.width, height: fileItem.thHeight && fileItem.thHeight.height},
        id: fileItem.id
      }
    };

    FileManagerService.mkdir({}, form, function(data){
      console.log(data);
    });
  }


  $scope.discard = function(){
    history.back();
  };
})
.controller('EditArticleCtrl', function($scope, $state, $timeout, Categories, ArticleService, Upload, $rootScope, Unsaved,myModal, FileManagerService, DataDictService){
  $scope.ArticleForm = {
    title:"更新文章"
  };
  $scope.article = Categories || {};
  $scope.videos = [{type: '', url: ''}];
  $rootScope.multiple = true;
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.article.title, width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.article.icons.splice(i, 1);
      }
    });
  };

  var watcher = $scope.$watch("article", function(newVal, oldVal){
    if(newVal){
      watcher();
      init();
      $scope.loadVideoTypes();

      $timeout(function(){
        $scope.article.categoryList = getCategoryTree(Categories.categoryList || []);
        $scope.article.category = Categories.categoryId;
        $scope.article.isPublic = Categories.public+'';
        $scope.article.isOriginal = Categories.original;
        $scope.article.isTop = Categories.top;
        $scope.article.isRecommend = Categories.recommned;
        $scope.selectedTags = ($scope.article.keyword && $scope.article.keyword.join(' ')) || "";
        if(Unsaved.content){
          $scope.article.content = Unsaved.content;
        }
        $scope.article.content = Yihu.util.restoreRawHtml($scope.article.content);
        // if (Categories.source) {
        //   $scope.article.source = Yihu.util.restoreRawHtml($scope.article.source);
        // }
        if (Categories.wxSharePic) {
          $scope.article.wxiconurl = Yihu.util.setContext($scope.downloadUrl, Categories.wxSharePic+"?w=80");
        }
        if (Categories.relates && Categories.relates.length) {
          $rootScope.selectedProducts = Categories.relates;
        } else {
          $rootScope.selectedProducts = [];
        }

        if($scope.article.icons){
          for(var i=0; i<$scope.article.icons.length; i++){
            var p = $scope.article.icons[i];
            var pid = $scope.article.icons[i].id;
            $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: p.width, height: p.height});
          }
        }else{
          $scope.article.icons = [];
        }
        if (Categories.videos && Categories.videos.length) {
          $scope.videos = Categories.videos;
        }
      }, 500);
    }
  });

  function getCategoryTree(cats) {
    var root = [];
    for(var i=0; i<cats.length; i++) {
      var item = cats[i];
      if (item.parentId == '0') {
        root.push(item);
      }
    }
    for(var j=0; j<cats.length; j++) {
      var node = cats[j];
      if (node.parentId != '0') {
        var idx = getTreeIndex(root, node);
        if (idx >= 0) {
          node.name = '　　|---' + node.name;
          root.splice(idx + 1, 0, node); 
        }
      }
    }
    return root;
  }

  function getTreeIndex(root, node) {
    for (var i=0; i<root.length; i++) {
      if (root[i].id == node.parentId) {
        return i;
      }
    }
    return -1;
  }
  $scope.loadVideoTypes = function(){
    DataDictService.getChildren({
      parentPath: 'cms/config/videotype'
    }, function(data){
      $scope.videoTypes = data.childrens || [];
    });
  };
  $scope.addVideo = function(){
    $scope.videos.push({type: '', url: ''});
  };
  $scope.removeVideo = function(index) {
    if (index && $scope.videos.length > index) {
      $scope.videos.splice(index, 1);
    }
  };

  // upload on files select or drop
  $scope.upload  = function (files) {
    if(!files){
      return;
    }
    var uploadTotal = $scope.article.layout == 'small' ? 2 : 1;
    if(($scope.article.icons && $scope.article.icons.length >= uploadTotal) || (files && files.length > uploadTotal)){
      alert('已超过文件上传阈值，最多上传' + uploadTotal + '个文件!');
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    if (files && files.length) {
      $scope.showDialog = true;

      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.article.icons.push({
                id: data.id, 
                width: data.width,
                height: data.height,
                thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
                thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };
  
  $scope.submitForm = function(){
    if ($scope.videos.length === 1 && $scope.videos[0].url === '') {
      $scope.videos = [];
    }
    var articleForm = {
      title:$scope.article.title,
      subTitle:$scope.article.subTitle,
      categoryId: $scope.article.category,
      categoryName:$("select[name='category']").find("option:selected").text().replace('　　|---', ''),
      author:$scope.article.author,
      content:Yihu.util.replaceLazyHtml($scope.article.contentBody),
      keyword:($scope.selectedTags && $scope.selectedTags.split(" ")) || [],
      summary:$scope.article.summary,
      relates: $rootScope.selectedProducts,
      relateTile: $scope.article.relateTile,
      videoTitle: $scope.article.videoTitle,
      wxSharePic: $scope.article.wxSharePic,
      public:$("input[name='isPublic']").prop('checked'),
      recommned:$("input[name='isRecommend']").prop('checked'),
      top:$("input[name='isTop']").prop('checked'),
      original:$("input[name='isOriginal']").prop('checked'),
      status: 1,
      icons: $scope.article.icons,
      sort:$scope.article.sort,
      pv:$scope.article.pv,
      editor: $scope.article.editor,
      inputer: $scope.article.inputer,
      auditor: $scope.article.auditor,
      createBy:$scope.article.createBy,
      source:Yihu.util.replaceLazyHtml($scope.article.sourceBody),
      postTime:$("#postTime").val(),
      contentId:$scope.article.contentId,
      layout: $scope.article.layout,
      videos: $scope.videos,
      type: $state.params.type || 1
    };
    ArticleService.update({id: $state.params.id}, articleForm, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      history.back();
    });
  };

  $scope.saveForm = function(){
    if ($scope.videos.length === 1 && $scope.videos[0].url === '') {
      $scope.videos = [];
    }
    var articleForm = {
      title:$scope.article.title,
      subTitle:$scope.article.subTitle,
      categoryId: $scope.article.category,
      categoryName:$("select[name='category']").find("option:selected").text().replace('　　|---', ''),
      author:$scope.article.author,
      content:Yihu.util.replaceLazyHtml($scope.article.contentBody),
      keyword:($scope.selectedTags && $scope.selectedTags.split(" ")) || [],
      summary:$scope.article.summary,
      relates: $rootScope.selectedProducts,
      relateTile: $scope.article.relateTile,
      videoTitle: $scope.article.videoTitle,
      wxSharePic: $scope.article.wxSharePic,
      public:$("input[name='isPublic']").prop('checked'),
      recommned:$("input[name='isRecommend']").prop('checked'),
      top:$("input[name='isTop']").prop('checked'),
      original:$("input[name='isOriginal']").prop('checked'),
      status: 2,
      icons: $scope.article.icons,
      sort:$scope.article.sort,
      pv:$scope.article.pv,
      editor: $scope.article.editor,
      inputer: $scope.article.inputer,
      auditor: $scope.article.auditor,
      createBy:$scope.article.createBy,
      source:Yihu.util.replaceLazyHtml($scope.article.sourceBody),
      postTime:$("#postTime").val(),
      contentId:$scope.article.contentId,
      layout: $scope.article.layout,
      videos: $scope.videos,
      type: $state.params.type || 1
    };
    ArticleService.update({id: $state.params.id}, articleForm, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      history.back();
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=150"),width: width, height: height});
            $scope.article.icons.push({ id: id, width: width, height: height, 
              thWidth: { width: box.data("thwidthWidth") || "", height: box.data("thwidthHeight") || ""}, 
              thHeight: { width: box.data("thheightWidth") || "", height: box.data("thheightHeight") || ""} 
            });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order:"name",
      desc:1,
      // type:"image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };
  $scope.removeProduct = function(idx) {
    if ($rootScope.selectedProducts && $rootScope.selectedProducts.length > idx) {
      $rootScope.selectedProducts.splice(idx, 1);
    }
  };
  $scope.cleanProducts = function() {
    $rootScope.selectedProducts = [];
    $rootScope.multiSelectProducts = [];
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.multiple = false;
    $rootScope.multiSelectProducts = [];
    $rootScope.selectedProducts = [];
  });

  function uploadedCallback(fileName, fileItem){
    var form = {
      path: '/product/默认库', 
      fileName: fileName,
      fileType: guessFileType(fileName),
      picture: {
        width: fileItem.width,
        height: fileItem.height,
        thWidth: { width: fileItem.thWidth && fileItem.thWidth.width, height: fileItem.thWidth && fileItem.thWidth.height},
        thHeight: { width: fileItem.thHeight && fileItem.thHeight.width, height: fileItem.thHeight && fileItem.thHeight.height},
        id: fileItem.id
      }
    };

    FileManagerService.mkdir({}, form, function(data){
      console.log(data);
    });
  }

  $scope.uploadPic = function (file) {
    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      if(data.code===0){
        uploadedCallback(data.fileName, data);
        $timeout(function(){
          $scope.article.wxiconurl = data.url+"?w=80";
          $scope.article.wxSharePic = data.id;
        });
      }
    }, function (resp) {
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progressPercentage + '% ');
    });
  };

})
.controller('ViewArticleCtrl', function($scope, $state, $timeout, Article){
  $scope.article = Article || {};
  $scope.article.icon = Yihu.util.setContext($scope.downloadUrl, Article.icon ? Article.icon : '');
  
  var watcher = $scope.$watch("article.title", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        $scope.article = Article;
        var html = Article.content;
        let prefix = 'http://pe1975mall.yihuyixi.com';
        let imgs = document.getElementById('content').getElementsByTagName('img') || [];
        for (let i = 0; i < imgs.length; i++) {
          let img = imgs[i];
          let src = img.getAttribute('data-original');
          if (src) {
            let width = img.getAttribute('width');
            let height = img.getAttribute('height');
            let key = 'img class="lazy" data-original="' + src + '" src=""';
            let suffix = '';
            if (width) {
              suffix += ' width="' + width + '"';
            }
            if (height) {
              suffix += ' height="' + height + '"';
            }
            let key2 = key + ' alt=""' + suffix;
            key += suffix;
            if (src.indexOf('http:') < 0 && src.indexOf('https:') < 0) {
              src = prefix + src;
            } else {
              src = src.replace('http://www.yihuyixi.com', prefix);
            }
            if (src.lastIndexOf('?') < 0) {
              src += '?1';
            }
            src = src + '&w=750';
            html = html.replace(key, 'img src="' + src + '" ').replace(key2, 'img src="' + src + '"');
          } else {
            let pic = img.getAttribute('src');
            let width = img.getAttribute('width');
            let height = img.getAttribute('height');
            let suffix = '';
            if (width) {
              suffix += ' width="' + width + '"';
            }
            if (height) {
              suffix += ' height="' + height + '"';
            }
            let p1 = suffix + ' alt="" src="' + pic + '"';
            let p2 = suffix + ' src="' + pic + '"';
            if (pic.indexOf('http:') < 0 && pic.indexOf('https:') < 0) {
              pic = prefix + pic;
            } else {
              pic = pic.replace('http://www.yihuyixi.com', prefix);
            }
            if (pic.lastIndexOf('?') < 0) {
              pic += '?1';
            }
            pic = pic + '&w=750';
            html = html.replace(p1, ' src="' + pic + '" ').replace(p2, 'img src="' + pic + '"');
          }
        }
        $scope.article.content = html;

      }, 500);
    }
  });
});

/**
 * 分类管理模块
 * @type {[type]}
 */
var categoryListModule = angular.module("CategoryListModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns']); 
categoryListModule.controller('CategoryListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, CategoryService, $rootScope) {

  $scope.CategoryForm = {
    title:'文章类别'
  };

  // var paginationOptions = {
  //   pageNumber:1,
  //   pageSize:5,
  //   sort:null
  // };

  // $scope.gridOptions = {
  //   paginationPageSizes: [5, 10, 50, 100],
  //   paginationPageSize: 5,
  //   useExternalPagination: true,
  //   useExternalSorting: true,
  //   enableSorting: false,
  //   showGridFooter: true,
  //   enableGridMenu: true,
  //   enableFiltering: false,
  //   enableRowSelection: true,
  //   enableSelectAll: true,
  //   multiSelect:true    
  // };

  //搜索
  $scope.search = function(){
    getPage();
  };
  
  // $scope.gridOptions.onRegisterApi = function(gridApi){
  //   $scope.gridApi = gridApi; 
  //   $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
  //     if (sortColumns.length === 0) {
  //       paginationOptions.sort = null;
  //     }else{
  //       paginationOptions.sort = sortColumns[0].sort.direction;
  //     }
  //     getPage();
  //   });

  //   gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
  //     paginationOptions.pageNumber = newPage;
  //     paginationOptions.pageSize = pageSize;
  //     getPage();
  //   });
  //   init();
  // };
  
  // $scope.gridOptions.columnDefs = [{
  //     field: 'name',
  //     displayName: '文章类别',
  //   }, {
  //     field: 'parentId',
  //     displayName: '父级类别',
  //   }, {
  //     field: 'sort',
  //     displayName: '排序',
  //   }, {
  //     name: 'id',
  //     displayName: '操作',
  //     cellTemplate: '<a class="btn-small" href="#/article/category/edit/{{COL_FIELD}}">修改</a>',
  //     enableFiltering: false
  //   }
  // ];

  $scope.category = {};

  function fn(data, pid) {
    var result = [], temp;
    for (var i = 0; i < data.length; i++) {
      if (data[i].parentId == pid) {
        var obj = {"name": data[i].name,"id": data[i].id};
        temp = fn(data, data[i].id);
        if (temp.length > 0) {
          obj.children = temp;
        }
        result.push(obj);
      }
    }
    return result;
  }

  $scope.selectedTreeItems = [];
  $scope.tree = [];
    
  $scope.itemCheckedChanged = function($item){
    console.log($item,'item checked');
    $scope.selectedTreeItems = [];
    if($item.$$isChecked){
      $scope.selectedTreeItems.push($item.id);
    }else{
      var index = $.inArray($item.id, $scope.selectedTreeItems);
      $scope.selectedTreeItems.splice(index, 1);
    }
  };

  //分页查询
  var getPage = function() {
    var categoryForm = {
      // currentPage:paginationOptions.pageNumber, 
      // pageSize:paginationOptions.pageSize, 
      currentPage: 1, 
      pageSize: 10000,
      name:$scope.category.name
    };
    CategoryService.getList({}, categoryForm, function(data){
      // $scope.gridOptions.totalItems = data.total || 0;
      // var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      // $scope.gridOptions.data = data.categories || [];
      $scope.tree = fn(data.categories || [], '0');
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if($rootScope.nestedAnimated){
      $rootScope.nestedAnimated = false;
      $rootScope.currentAnimated = false;
    }else if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  $scope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $rootScope.nestedAnimated = true;
    $state.go('^');
  };

  //初始化
  function init(){
    $("#myModal").remove();
    $(".modalDialog").remove();  

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });

    myModal.loadTemplateUrl('template/modal/modal.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "系统提示",
        body:'<p>只允许同一时间更新一个类别！</p>',
        buttons:{ YES: '确定'},
        ok:function(){
          $(".modalDialog").modal('hide');         
        }
      };
    });

    getPage();
  }

  init();

  $scope.update = function(){
    var selectedItems = $scope.selectedTreeItems;
    console.log(selectedItems);
    if(selectedItems && selectedItems.length==1){
      $rootScope.$location.path('/article/category/edit/'+selectedItems[0]);
    }else{
      $(".modalDialog").modal('show');
    }
  };
  
  //删除
  $scope.remove = function(){
    if($scope.selectedTreeItems && $scope.selectedTreeItems.length){
      $('#myModal').modal('show');
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    var rows = $scope.selectedTreeItems;
    if(rows && rows.length){
      for(var i=0; i<rows.length; i++){
        CategoryService.remove({
          id:rows[i]
        }, function(){
          getPage();
        });
      }
    }
    $('#myModal').modal('hide');
  };
})
.controller('AddCategoryCtrl', function($scope, $state, CategoryService, $rootScope){
  $scope.CategoryForm = {
    title:"新增分类"
  };
  
  $scope.category = {
    parentId:'0'
  };

  CategoryService.getList({}, {currentPage:1,pageSize:10000}, function(data){
    $scope.category.categoryList = getCategoryTree(data.categories);
  });

  function getCategoryTree(cats) {
    var root = [];
    for(var i=0; i<cats.length; i++) {
      var item = cats[i];
      if (item.parentId == '0') {
        root.push(item);
      }
    }
    for(var j=0; j<cats.length; j++) {
      var node = cats[j];
      if (node.parentId != '0') {
        var idx = getTreeIndex(root, node);
        if (idx >= 0) {
          node.name = '　　|---' + node.name;
          root.splice(idx + 1, 0, node); 
        }
      }
    }
    return root;
  }
  
  function getTreeIndex(root, node) {
    for (var i=0; i<root.length; i++) {
      if (root[i].id == node.parentId) {
        return i;
      }
    }
    return -1;
  }

  $scope.submitForm = function(){
    var categoryForm = {
      name: $scope.category.name,
      sort: $scope.category.sort,
      parentId: $scope.category.parentId
    };

    CategoryService.create({}, categoryForm, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditCategoryCtrl', function($scope, $state, $timeout, Categories, CategoryService, $rootScope){
  $scope.CategoryForm = {
    title:"更新分类"
  };

  $scope.category = Categories || {};
  var watcher = $scope.$watch("category.name", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        $scope.category.categoryList = getCategoryTree(Categories.categoryList);
        $scope.category.parentId = Categories.parentId;
        $("select[name='parentId']").val(Categories.parentId);
      }, 50);
    }
  });

  function getCategoryTree(cats) {
    var root = [];
    for(var i=0; i<cats.length; i++) {
      var item = cats[i];
      if (item.parentId == '0') {
        root.push(item);
      }
    }
    for(var j=0; j<cats.length; j++) {
      var node = cats[j];
      if (node.parentId != '0') {
        var idx = getTreeIndex(root, node);
        if (idx >= 0) {
          node.name = '　　|---' + node.name;
          root.splice(idx + 1, 0, node); 
        }
      }
    }
    return root;
  }
  
  function getTreeIndex(root, node) {
    for (var i=0; i<root.length; i++) {
      if (root[i].id == node.parentId) {
        return i;
      }
    }
    return -1;
  }

  $scope.submitForm = function(){
    var categoryForm = {
      name: $scope.category.name,
      sort: $scope.category.sort,
      parentId: $scope.category.parentId
    };

    CategoryService.update({id: $state.params.id}, categoryForm, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
});

/**
 * 文件管理模块
 * @type {[type]}
 */
var filesListModule = angular.module("FilesListModule", []);
filesListModule.controller('FilesListCtrl',function($scope, $timeout, FileManagerService, Upload, myModal, $rootScope, dateFilter){
  var searchOptions = {};  
  // $scope.selectedTags = "同事 家人 好友";
  
  var breadcrumbs = $scope.breadcrumbs = [];
  var nav = $scope.nav = {
    current: '',
    prev: ''
  };
  breadcrumbs.push({label:'全部文件', link:nav.current, icon:"fa fa-navicon"});

  $scope.gridData = {};
  getList();

  $scope.opbar = {
    checkNum:0, //选中数量
    showToolbar:false   //显示扩展工具条：删除、重命名、移动、复制等
  };

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      nav.prev = nav.current;
      nav.current = nav.current+'/'+item.fileName;
      
      breadcrumbs.push({label:item.fileName, link:nav.current});
      getList();
    }
  };

  $scope.backPrev = function(){
    breadcrumbs = breadcrumbs.slice(0, breadcrumbs.length-1);
    nav.current = nav.prev;

    if(breadcrumbs.length>1){
      nav.prev = breadcrumbs[breadcrumbs.length-2].link;
    }else{
      nav.prev = '';
    }
    $scope.breadcrumbs = breadcrumbs;
    getList();
  };

  $scope.images = []; 
  function getList(){
    reset();

    searchOptions.type = $("#btnFileTypes>button.btn-primary").data('type');
    searchOptions.tag = $scope.selectedTags;
    searchOptions.path = nav.current;
    searchOptions.startDate = $("#beginTime").val();
    searchOptions.endDate = $("#endTime").val();
    $rootScope.$location.search(searchOptions);
    var opts = {
      order:"name",
      desc:1
    };
    angular.extend(opts, searchOptions);

    FileManagerService.getList(opts, function(data){
      reset();
      $scope.gridData.files = (data.info && data.info.files) || [];

      $scope.images.splice(0, $scope.images.length);
      var files = $scope.gridData.files;
      for(var i=0; i<files.length; i++){
        var item = files[i];
        if("image"===item.fileType){
          $scope.images.push({
            link: item.picture ? ($scope.downloadUrl + (item.picture && item.picture.id)) : '',
            title: item.fileName,
            width: item.picture && item.picture.width,
            height: item.picture && item.picture.height,
            directory: item.parentFolder,
            createdAt: dateFilter(item.createTime, 'yyyy-MM-dd HH:mm:ss')
          });
        }
      }
      $scope.reloadImage($scope.images);
      $scope.previewLoaded = true;
      if(!$scope.$$phase){
        $scope.$apply();
      }
    });
  }

  $scope.gogo = function(val){
    var idx = -1;
    for(var i=0,len=breadcrumbs.length; i<len; i++){
      if(val == breadcrumbs[i].label){
        idx = i;
      }
    }
    nav.current = breadcrumbs[idx].link;
    nav.prev = idx===0 ? '' : breadcrumbs[idx-1].link;
    $scope.breadcrumbs = breadcrumbs = breadcrumbs.slice(0, idx+1);
    getList();
  };

  function reset(){
    $timeout(function(){
      $scope.opbar.checkNum = 0;
      $scope.opbar.showToolbar = false;
    });
    $(".item-checked").removeClass("item-checked");
  }

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  $scope.search = function(){
    getList();
  };

  $scope.createFolder = function(){
    reset();
    var item = {
      "fileName":"新建文件夹",
      "fileType":"folder",
      "isDirectory":true, 
      "creating":true
    };

    if($scope.gridData.files && $scope.gridData.files.length){
      $scope.gridData.files.splice(0, 0, item);
    }else{
      $scope.gridData.files.push(item);
    }

    setTimeout(function(){
      var input = $(".create-folder:eq(0)").children("input");
      input.select();
      input.focus();
    }, 50);
  };

  /**
   * 执行文件夹创建， 如果需要事件传播， 传入$event
   *  var keyCode = $event.keyCode || $event.which;
      //enter key
      if(keyCode == '13'){
      }
   * @param  {[type]} $event [description]
   * @param  {[type]} item   [description]
   * @return {[type]}        [description]
   */
  $scope.doCreateFolder = function($event, item){
    if(!$event){
      return;
    }

    var keyCode = $event.keyCode || $event.which;
    //enter key
    if(keyCode == '13'){
      $scope.fireCreateFolder(item);
    }
  };

  $scope.fireCreateFolder = function(item){
    if(item && item.fileName){
      item.creating = false;
      reset();

      if(item.rename){
        item.rename = false;
        var renameForm = {
          // path: nav.current, 
          fId: item.id,
          newFileName: item.fileName
        };
        FileManagerService.rename({}, renameForm, function(){
          reloadDirTree();
        });
      }else{ 
        var form = {
          path: nav.current, 
          fileName: item.fileName
        };
        FileManagerService.mkdir({}, form, function(){
          reloadDirTree();
        });
      }
    }
  };

  /** 取消创建文件夹 */
  $scope.discardFolder = function(item){
    if(item.id){
      item.creating = false;
    }else{
      $scope.gridData.files.splice(0, 1);
    }
    reset();
  };

  var items = [];
  $scope.tree = [];
  reloadDirTree();

  function reloadDirTree(){
    FileManagerService.dirTree(function(data){
      $scope.tree = data.info || [];

      node($scope.tree, '/', items);
    });
  }

  function node(arr, parent, items){
    for(var i=0; i<arr.length; i++){
      items.push({id:arr[i].id, path:parent+arr[i].name});
      
      var item = arr[i].children;
      if(item && item.length){
        node(item, parent+arr[i].name+"/", items);
      }
    }
  }

  function findTreeNodeById(id){
    if(items.length===0){
      node($scope.tree, '/', items);
    }

    for(var i=0; i<items.length; i++){
      if(items[i].id==id){
        return items[i];
      }
    }
  }
    
  $scope.itemClicked = function ($item) {
    $("#selectedTreeNode").val($item.id);
    // console.log($item, 'item clicked');
  };
  
  $scope.itemCheckedChanged = function($item){
    // console.log($item,'item checked');
  };
        
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };

      $scope.submitConfirm = removed;
    });

    $("#myDialog").remove();
    myModal.loadTemplateUrl('template/modal/treeDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "移动到",
        buttons:{ YES: '确定', NO: '关闭'},
        ok:move
      };
    });
  }
  init();

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    $("#myModal").remove();
    $("#myDialog").remove();
    $(".modal-backdrop").remove();
  });

  /** 下载文件 */
  $scope.download = function(){
    var selectedFile = $(".file > .item-checked");
    if(selectedFile && selectedFile.data("type")=='folder'){
      alert('抱歉，系统暂不支持文件夹下载！');
      return;
    }
    var id = selectedFile.data("picture");
    if (id) {
      id += '?' + new Date().getTime();
    }
    $('iframe[name="downloadIframe"]').remove();
    var iframe = '<iframe name="downloadIframe" src="about:blank" style="width:0px; height:0px; "></iframe>';
    var psCtx = $rootScope.options.fileServerUrl; 
    var form = '<form action="' + psCtx + id+'" method="GET" target="downloadIframe" name="myform"></form>';
    $(iframe).appendTo(document.body);
    $(form).appendTo(document.body).submit().remove();
  };

  $scope.pictureurl = function() {
    var selectedFile = $(".file > .item-checked");
    if(selectedFile && selectedFile.data("type")=='folder'){
      alert('抱歉，系统暂不支持文件夹下载！');
      return;
    }
    alert($rootScope.options.fileServerUrl + selectedFile.data("picture"));
  };

  /** 删除文件 */
  $scope.remove = function(){
    $('#myModal').modal('show');
  };

  /** 复制到 */
  $scope.copyTo = function(){
    $scope.dialog = {
      title: "复制到",
      buttons:{ YES: '确定', NO: '关闭'},
      ok:copy
    };
    $("#myDialog").modal('show');
    $("#selectedTreeNode").val('');
  };

  function copy(){
    var files = [];
    $(".file > .item-checked").map(function(){
      var self = $(this);
      if(self.data("id")){
        var file = {};
        file.fileName = self.attr("title");
        file.fileType = self.data("type");
        if(file.fileType=='folder'){
          file.isDirectory = true;
        }else{
          file.picture = {
            id: self.data("picture"),
            width: self.data("width"),
            height: self.data("height"),
            thHeight: {width: self.data("thheightWidth"), height: self.data("thwidthHeight")},
            thWidth: {width: self.data("thwidthWidth"), height: self.data("thwidthHeight")}
          };
        }
        files.push(file);
      }
    });

    var selectedTreeNodeId = $("#selectedTreeNode").val();
    if(!selectedTreeNodeId){
      $("#myDialog").modal('hide');
      return;
    }
    var treeNode = findTreeNodeById(selectedTreeNodeId);
    FileManagerService.copy({dest: treeNode.path}, files, function(data){
      $("#myDialog").modal('hide');
    });
  }

  function move(){
    var files = [];
    $(".file > .item-checked").map(function(){
      if($(this).data("id")){
        var file = {};
        file.id = $(this).data("id");
        files.push(file);
      }
    });

    var selectedTreeNodeId = $("#selectedTreeNode").val();
    if(!selectedTreeNodeId){
      $("#myDialog").modal('hide');
      return;
    }
    var treeNode = findTreeNodeById(selectedTreeNodeId);
    FileManagerService.move({dest: treeNode.path}, files, function(data){
      $("#myDialog").modal('hide');
      // $rootScope.$window.location.reload(true);
      reset();
      getList();
    });
  }

  function removed(){
    // var selectedIds = [];
    var selectedNodes = $(".file > .item-checked").map(function(){
      // var index = $(this).data("index");
      // if(index>=0){
      //   selectedIds.push(index);
      // }
      return $(this).data("id");
    }).get();

    var files = [];
    if(selectedNodes && selectedNodes.length){
      for(var i=0; i<selectedNodes.length; i++){
        if(selectedNodes[i]){
          var file = {};
          file.id = selectedNodes[i];
          files.push(file);
        }
      }

      FileManagerService.remove({}, files, function(data){
        $("#myModal").modal('hide');

        var tmpArray = $scope.gridData.files;
        for(var i=0; i<tmpArray.length; i++){
          var file = tmpArray[i];

          for(var j=0; j<selectedNodes.length; j++){
            var id = selectedNodes[j];
            if(id === file.id){
              tmpArray.splice(i, 1);
              i--;
            }
          }
        }
        $scope.gridData.files = tmpArray;
        reset();
        getList();
        reloadDirTree();
        // $rootScope.$window.location.reload(true);
      });
    }else{
      $("#myModal").modal('hide');
    }
  }

  function getSelectedNodes(){
    return $(".file > .item-checked").map(function(){return $(this).data("id");}).get();
  }

  /** 移动到 */
  $scope.moveTo = function(){
    $scope.dialog = {
      title: "移动到",
      buttons:{ YES: '确定', NO: '关闭'},
      ok:move
    };
    $("#myDialog").modal('show');
    $("#selectedTreeNode").val('');
  };

  /** 重命名 */
  $scope.rename = function(){
    var index = $(".file > .item-checked").data("index");
    if(typeof index != 'undefined'){
      $scope.gridData.files[index].creating = true;
      $scope.gridData.files[index].rename = true;
    }
  };

  function guessFileType(fileName){
    if(!fileName){
      return '';
    }

    var suffix = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
    var videos = ['.mpeg','.mpg','.avi','.mov','.mpg','.mkv','.rm','.rmvb','.wmv','.asf','.mov','.mp4','.asf','.3gp','.dmv','.mtv'];
    var images = ['.jpg','.jpeg','.bmp','.png','.gif','.tiff'];
    if(videos.indexOf(suffix) >= 0){
      return "video";
    }else if(images.indexOf(suffix)>= 0){
      return "image";
    }else if(".swf"==suffix){
      return "flash";
    }
    return "file";
  }


  function getFileIndex(files, file){
    if(!file){
      return -1;
    }

    if(files && files.length){
      for(var i=0; i<files.length; i++){
        if(file.$$hashKey){
          if(files[i].$$hashKey==file.$$hashKey && files[i].name==file.name){
            return i;
          }
        }else{
          if(files[i].name==file.name){
            return i;
          }
        }
      }
    }
  }

  // upload on files select or drop
  $scope.uploadFiles  = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };

    if (files && files.length) {
      $scope.showDialog = true;
      uploadTask.inprocess = true;
      // uploadTask.files.splice(0, uploadTask.files.length);

      for(var i=0; i < files.length; i++){
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        var fileName = files[i].name;
        var fileType = guessFileType(fileName);

        Upload.upload({
          url: $scope.uploadUrl,
          data: {file: files[i]}
        }).then(function (resp) {
          var data = resp.data;

          for(var k=0, len=data.length; k<len; k++){
            var fileItem = data[k];
            var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
            if(idx>=0){
              uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
            }

            if(fileItem && fileItem.code===0){
              uploadedCallback(fileItem.fileName, fileType, fileItem);
              // console.log('Success ' + fileItem.url + ' uploaded. ');
            }else{
              console.log('Upload failed, caused by '+ fileItem.info);
            }
          }

          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
      
    }
  };

  function uploadedCallback(fileName, fileType, fileItem){
    var form = {
      path: nav.current, 
      fileName: fileName,
      fileType: fileType,
      picture: {
        width: fileItem.width,
        height: fileItem.height,
        thWidth: { width: fileItem.thWidth && fileItem.thWidth.width, height: fileItem.thWidth && fileItem.thWidth.height},
        thHeight: { width: fileItem.thHeight && fileItem.thHeight.width, height: fileItem.thHeight && fileItem.thHeight.height},
        id: fileItem.id
      }
    };

    FileManagerService.mkdir({}, form, function(data){
      // $rootScope.$window.location.reload(true);
      getList();
    });
  }
  
});

/**
 * 客户管理模块
 * @type {[type]}
 */
var customerModule = angular.module("CustomerListModule", []);
customerModule.controller('CustomerListCtrl',function($scope, $state, $http, $q){
//  var canceller = $q.defer();
//  $http.get('/customer/list', {timeout:canceller.promise})
//  .success(function(data) {
//    $scope.customers = data.customers;
//    $scope.customerTotal = data.customerTotal;
//    $scope.companies = data.company;
//    $scope.companyTotal = data.companyTotal;
//  });
//  
//  $scope.$on('$destroy', function(){
//    canceller.resolve();  //如果http请求未完成，则终止
//  });
});

/**
 * 产品管理模块
 * @type {[type]}
 */
var productListModule = angular.module("ProductListModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns']);
productListModule.controller('ProductListCtrl', function($scope, $state, uiGridConstants, myModal, Artwork, ArtworkService, $rootScope, BasicService, Store){
  $scope.artwork = Artwork || {};

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true
  };

  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };

  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 
    if ($state.params.reset) {
      $scope.artwork.artworkType = $state.params.type || "";
      Store.localRemove('goodsSearch');
    } else {
      var lastSearch = JSON.parse(Store.localGet('goodsSearch') || '{}');
      paginationOptions.pageNumber = lastSearch.currentPage || 1; 
      paginationOptions.pageSize = lastSearch.pageSize; 
      $scope.artwork.name = lastSearch.name || '';
      $scope.artwork.artworkAuthor = lastSearch.authorId || '';
      $("select[name='artworkCategory']").val(lastSearch.categoryParentName || '');
      $scope.artwork.states = lastSearch.commodityStatesId || '';
      $scope.artwork.artworkType = lastSearch.artworkTypeName || '';
      $scope.artwork.priceWords = lastSearch.price || '';
      $scope.gridOptions.paginationCurrentPage = paginationOptions.pageNumber;
    }
    // $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
    //   if (sortColumns.length === 0) {
    //     paginationOptions.sort = null;
    //   }else{
    //     paginationOptions.sort = sortColumns[0].sort.direction;
    //   }
    //   getPage();
    // });

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });

    init();
  };
  $scope.gridOptions.columnDefs = [{
      field: 'pictures',
      displayName: '缩略图',
      width:80,
      cellTemplate: '<img ng-if="row.entity.pictures.length" ng-src="/ps/download/{{row.entity.pictures[0].id}}?w=80&h=80" class="artwork-icon"><img ng-if="!row.entity.pictures.length" src="images/defaultIcon.jpg" class="artwork-icon"></a>'
    }, {
      field: 'name',
      displayName: '商品名称',
      width:260
    },{
      field: 'artworkCategory.parent.value',
      displayName: '商品分类',
      width:90
    },{
      field: 'artworkCategory.value',
      displayName: '商品子分类',
      width:90
    },{
      field: 'artworkType.value',
      displayName: '商品类型',
      width:100
    }, {
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/products/edit/{{COL_FIELD}}?type={{row.entity.artworkType.name}}">修改</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="btn-small" href="#/products/models/{{row.entity.id}}?type={{row.entity.artworkType.name}}">产品款式管理</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="btn-small" href="#/products/{{row.entity.id}}/comments?type={{row.entity.artworkType.name}}">评论管理</a>',
      width:210,
      enableFiltering: false
    },{
      field: 'costPrice',
      displayName: '成本价',
      type:'number',
      width:80
    },{
      field: 'profitPrice',
      displayName: '毛利润',
      type:'number',
      width:80
    },{
      field: 'markPrice',
      displayName: '市场价',
      type:'number',
      width:80
    },{
      field: 'activityPrice',
      displayName: '活动价',
      type:'number',
      width:80
    },{
      field: 'commodityStates.name',
      displayName: '状态',
      width:80
    }, {
      field: 'user.name',
      displayName: '发布者',
      width:80
    }, {
      field: 'stock.total',
      displayName: '库存',
      width:80
    }, {
      field: 'stock.salesCount',
      displayName: '销售量',
      width:100
    }, {
      field: 'stock.status',
      displayName: '库存状态',
      width:100,
      cellFilter:'mapStockStatus'
    }, {
      field: 'isRecommend',
      displayName: '推荐',
      width:60
    }, {
      field: 'pv',
      displayName: 'PV',
      width:60
    }, {
      field: 'sorts',
      displayName: '排序',
      width:60
    }, {
      field: 'like',
      displayName: '收藏数',
      width:60
    }, {
      field: 'createTime',
      displayName: '发布日期',
      type: 'date',
      width:140
    }, {
      field: 'putOnShelvesTime',
      displayName: '上架时间',      
      type: 'date',
      width:140
    }
  ];

  $scope.loadCategoryList = function(){
    var key = $("select[name='artworkType']").find("option:selected").val() || $state.params.type;
    if(!key){
      return;
    }

    //加载商品类型
    BasicService.getArtworkCategory({ type: key }, function(data){
      $scope.artwork.categoryList = data && data.childrens;
    });
  };

  var getPage = function() {
    var params = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize,
      name: $scope.artwork.name,
      authorId: $scope.artwork.artworkAuthor,
      categoryParentName: $("select[name='artworkCategory']").val(),
      commodityStatesId: $scope.artwork.states,
      price: $scope.artwork.priceWords ? $scope.artwork.priceWords : (($scope.artwork.minPrice || $scope.artwork.maxPrice) ? ($scope.artwork.minPrice || 0) + '-' + ($scope.artwork.maxPrice || '') : ''),
      artworkTypeName: $scope.artwork.artworkType || $state.params.type || "",
      fromCMS: true
    };
    ArtworkService.getList(params, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var artworkData = data.artworks || [];
      
      angular.forEach(artworkData, function(item){
        item.putOnShelvesTime = moment(item.putOnShelvesTime).format("YYYY-MM-DD HH:mm");
        item.createTime = moment(item.createTime).format("YYYY-MM-DD HH:mm");
      });
      $scope.gridOptions.data = artworkData;
      Store.localSave('goodsSearch', JSON.stringify(params));
    });
    $scope.loadCategoryList();
  };

  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  $scope.refreshCache = function() {
    ArtworkService.refreshCache({
      refreshRedis: true
    }, function(data) {
      alert('缓存刷新成功!');
    });
  }

  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        ArtworkService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };

})
.filter('mapStockStatus', function(){
  var statusHash = {
    0: '正常购买',
    1: '缺货预定',
    2: '无货提醒'
  };
  return function(input){
    return statusHash[input];
  };
})
.controller('AddProductCtrl', function($scope, $state,$timeout, Artwork, ArtworkService, Upload, $rootScope, Unsaved, BasicService, myModal, FileManagerService, DataDictService){
  $scope.ProductForm = {
    title:"新增艺术品"
  };
  $scope.artwork = Artwork || {};
  $scope.videos = [{type: '', url: ''}];
  $rootScope.multiple = true;

  $scope.selectedTags = "";
  $scope.artwork.discountRate = 0.3;

  var watcher = $scope.$watch("artwork", function(newVal, oldVal){
    if(newVal){
      watcher();
      init();

      $timeout(function(){
        $scope.artwork = Artwork;
        $scope.artwork.id = Unsaved.id;
        if(Unsaved.content){
          $scope.artwork.content = Unsaved.content;
        }
        $scope.artwork.content = Yihu.util.restoreRawHtml($scope.artwork.content);
        $scope.artwork.discountRate = 0.3;
      }, 50);
    }
  });

  $scope.loadArtist = function(){
    $("select[name='artworkSubCategory']").addClass("hide");
    $scope.artwork.subCategoryList = [];
    $scope.artwork.artworkSubCategory = "";

    var key = $("select[name='artworkType']").find("option:selected").val();
    if(!key){
      return;
    }

    //加载商品类型
    BasicService.getArtworkCategory({ type: key }, function(data){
      // $scope.artwork.categoryList = data && data.childrens;
      $scope.artwork.categorys = data && data.childrens || [];

      angular.forEach($scope.artwork.categorys, function(item, idx){
        if(item.propertyName == 'brand') {
          $scope.artwork.brands = item.childrens || [];
          $scope.artwork.categorys.splice(idx, 1);
        }
      });
    });

    //加载商品艺术家, 雅集没有艺术家
    if(key === 'artwork'){
      $(".artist").show();
      $(".theme").show();
      $(".scene").show();
      $(".copyer").show();
      $(".tea").hide();
      $scope.getArtworkTheme(key); 
      $scope.getArtworkScene(key);
      BasicService.getArtist({type: key}, function(data){
        $scope.artwork.artistList = data && data.childrens;
      });
    }else{
      $(".artist").hide();
      $(".theme").hide();
      $(".scene").hide();
      $(".copyer").hide();
      $(".tea").show();
      $scope.artwork.artistList = [];
    }
  };

  $scope.filterChildCategory = function() {
    $scope.loadParams($scope.artwork.category);
    $scope.artwork.childCategoryList = [];
    $scope.artwork.sunCategoryList = [];
    $scope.artwork.childCategory = '';
    $scope.artwork.sunCategory = '';
    angular.forEach($scope.artwork.categorys, function(item){
      if(item.propertyName == $scope.artwork.category) {
        $scope.artwork.childCategoryList = item.childrens || [];
      }
    });
  };

  $scope.filterSunCategory = function() {
    $scope.loadParams($scope.artwork.category + '_' + $scope.artwork.childCategory, true);
    $scope.artwork.sunCategoryList = [];
    $scope.artwork.sunCategory = '';
    angular.forEach($scope.artwork.childCategoryList, function(item){
      if(item.propertyName == $scope.artwork.childCategory) {
        $scope.artwork.sunCategoryList = item.childrens || [];
      }
    });
  };

  $scope.loadSubCategory = function(){
    var type = $("select[name='artworkType']").find("option:selected").val();
    var cat = $("select[name='artworkCategory']").find("option:selected").val();
    var children = $("select[name='artworkCategory']").find("option:selected").attr("children");
    if(!type || !cat || children == '0'){
      $("select[name='artworkSubCategory']").addClass("hide");
       $scope.artwork.subCategoryList = [];
       $scope.artwork.artworkSubCategory = "";
      return;
    }

    //加载商品子类型
    BasicService.getArtworkSubCategory({ type: type, category: cat}, function(data){
      var list = data && data.childrens;
      if(list && list.length){
        $("select[name='artworkSubCategory']").removeClass("hide").show();
        $scope.artwork.subCategoryList = list;
      }else{
        $("select[name='artworkSubCategory']").hide();
      }
    });
  };
  $scope.filterChildBrand = function() {
    $scope.artwork.childBrandList = [];
    $scope.artwork.childBrand = '';
    $scope.artwork.sunBrandList = [];
    $scope.artwork.sunBrand = '';
    angular.forEach($scope.artwork.brands, function(item){
      if(item.propertyName == $scope.artwork.brand) {
        $scope.artwork.childBrandList = item.childrens || [];
      }
    });
  };
  $scope.filterSunBrand = function() {
    $scope.artwork.sunBrandList = [];
    $scope.artwork.sunBrand = '';
    angular.forEach($scope.artwork.childBrandList, function(item){
      if(item.propertyName == $scope.artwork.childBrand) {
        $scope.artwork.sunBrandList = item.childrens || [];
      }
    });
  };

  $scope.getArtworkTheme = function(type){
    $scope.artwork.subjectList = [];
    $scope.artwork.subject = "";
    BasicService.getArtworkTheme({type: type}, function(data){
      var list = data && data.childrens;
      if(list && list.length){
        $("." + data.propertyName).show();
        $scope.artwork.subjectList = list;
      }else{
        $("." + data.propertyName).hide();
      }
    }, function(){
      $(".theme").hide();
    });
  };

  $scope.loadYearOptions = function(){
    DataDictService.getChildren({
      parentPath: 'cms/basedata/tea/year'
    }, function(data){
      $scope.artwork.yearList = data.childrens;
    });
  };
  $scope.loadQualityOptions = function(){
    DataDictService.getChildren({
      parentPath: 'cms/basedata/tea/quality'
    }, function(data){
      $scope.artwork.qualityList = data.childrens;
    });
  };
  $scope.loadCfOptions = function(){
    DataDictService.getChildren({
      parentPath: 'cms/basedata/tea/cf'
    }, function(data){
      $scope.artwork.cfList = data.childrens;
    });
  };
  $scope.loadParams = function(catName, noAction){
    DataDictService.getChildren({
      parentPath: 'cms/product/category/' + catName
    }, function(data){
      if (data.childrens && data.childrens.length) {
        $scope.parameters = data.childrens;
        $scope.parameters.forEach(function(item) {
          if (item.css === 'textarea') {
            item.key = item.desc;
          }
        });
        $scope.hasParameters = true;
      } else if (!noAction){
        $scope.hasParameters = false;
      }
    });
  };
  $scope.loadVideoTypes = function(){
    DataDictService.getChildren({
      parentPath: 'cms/config/videotype'
    }, function(data){
      $scope.videoTypes = data.childrens || [];
    });
  };
  $scope.addVideo = function(){
    $scope.videos.push({type: '', url: ''});
  };
  $scope.removeVideo = function(index) {
    if (index && $scope.videos.length > index) {
      $scope.videos.splice(index, 1);
    }
  };
  function initData() {
    $scope.loadYearOptions();
    $scope.loadQualityOptions();
    $scope.loadCfOptions();
    $scope.loadVideoTypes();
  }  

  $scope.getArtworkScene = function(type){
    $scope.artwork.sceneList = [];
    $scope.artwork.theme = "";
    BasicService.getArtworkScene({type: type}, function(data){
      var list = data && data.childrens;
      if(list && list.length){
        $("." + data.propertyName).show();
        $scope.artwork.sceneList = list;
      }else{
        $("." + data.propertyName).hide();
      }
    }, function(){
      $(".scene").hide();
    });
  };

  $scope.artwork.pictures = [];
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.artwork.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.artwork.pictures.splice(i, 1);
      }
    });
  };

  // upload on files select or drop
  $scope.upload  = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };

    if (files && files.length) {
      $scope.showDialog = true;

      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            uploadedCallback(fileItem.fileName, fileItem);
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.artwork.pictures.push({
                id: data.id, 
                width: data.width,
                height: data.height,
                thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
                thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };

  function uploadedCallback(fileName, fileItem){
    var form = {
      path: '/product/默认库', 
      fileName: fileName,
      fileType: guessFileType(fileName),
      picture: {
        width: fileItem.width,
        height: fileItem.height,
        thWidth: { width: fileItem.thWidth && fileItem.thWidth.width, height: fileItem.thWidth && fileItem.thWidth.height},
        thHeight: { width: fileItem.thHeight && fileItem.thHeight.width, height: fileItem.thHeight && fileItem.thHeight.height},
        id: fileItem.id
      }
    };

    FileManagerService.mkdir({}, form, function(data){
      console.log(data);
    });
  }

  $scope.uploadPic = function (file) {
    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      if(data.code===0){
        uploadedCallback(data.fileName, data);
        $timeout(function(){
          $scope.artwork.wxiconUrl = data.url+"?w=80";
          $scope.artwork.wxicon = data.id;
        });
      }
    }, function (resp) {
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progressPercentage + '% ');
    });
  };

  //初始化
  function init(){
    getList();
    initData();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=150"),width: width, height: height});
            $scope.artwork.pictures.push({ id: id, width: width, height: height, 
              thWidth: { width: box.data("thwidthWidth") || "", height: box.data("thwidthHeight") || ""}, 
              thHeight: { width: box.data("thheightWidth") || "", height: box.data("thheightHeight") || ""} 
            });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = "/product";
  function getList(){
    var opts = {
      order:"name",
      desc:1,
      // type:"image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };
  $scope.removeProduct = function(idx) {
    if ($rootScope.selectedProducts && $rootScope.selectedProducts.length > idx) {
      $rootScope.selectedProducts.splice(idx, 1);
    }
  };
  $scope.cleanProducts = function() {
    $rootScope.selectedProducts = [];
    $rootScope.multiSelectProducts = [];
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.multiple = false;
    $rootScope.multiSelectProducts = [];
    $rootScope.selectedProducts = [];
  });

  $scope.submitForm = function(){
    var weight = 0;
    $(".form-tags>span").map(function(){ 
      weight += $(this).data("weight") || 1;
    });
    if ($scope.videos.length === 1 && $scope.videos[0].url === '') {
      $scope.videos = [];
    }
    var artworkForm = {
      name: $scope.artwork.name,
      costPrice: $scope.artwork.costPrice,
      markPrice: $scope.artwork.markPrice,
      activityPrice: $scope.artwork.activityPrice,
      keyword: ($scope.selectedTags && $scope.selectedTags.split(" ")) || [],
      like: $scope.artwork.like,
      pv: $scope.artwork.pv,
      sorts: $scope.artwork.sorts,
      isRecommend: $("input[name='isRecommend']").prop('checked') ? 1 : 0,
      useCoupon: $("input[name='useCoupon']").prop('checked') ? 1 : 0,
      couponPercent: $("input[name='useCoupon']").prop('checked') && $scope.artwork.couponPercent || 0,
      storage: $("input[name='storage']").prop('checked'),
      years: $("input[name='storage']").prop('checked') ? $scope.artwork.years : 0,
      storeFee: $("input[name='storage']").prop('checked') ? $scope.artwork.storeFee : 0,
      videoUrl: $scope.artwork.videoUrl || '',
      commodityStates:{
        id: $scope.artwork.commodityStates,
        name: $("select[name='commodityStates']").find("option:selected").text()
      },
      artworkType:{
        name: $scope.artwork.artworkType,
        value: $("select[name='artworkType']").find("option:selected").text()
      },
      artworkAuthor:{
        name: $scope.artwork.artworkAuthor,
        value: $("select[name='artworkAuthor']").find("option:selected").text()
      },
      artworkCategory:{
        name: '',
        value: '',
        parent: {
          name: $scope.artwork.category,
          value: $("select[name='category']").find("option:selected").text()
        }
      },
      brand:{
        name: '',
        value: '',
        parent: {
          name: $scope.artwork.brand,
          value: $("select[name='brand']").find("option:selected").text()
        }
      },
      subject:{
        name:$scope.artwork.subject,
        value:$("select[name='subject']").find("option:selected").text()
      },
      scene:{
        name:$scope.artwork.scene,
        value:$("select[name='scene']").find("option:selected").text()
      },
      year:{
        name:$scope.artwork.year,
        value:$scope.artwork.year ? $("select[name='year']").find("option:selected").text() : ''
      },
      quality:{
        name:$scope.artwork.quality,
        value:$scope.artwork.quality ? $("select[name='quality']").find("option:selected").text() : ''
      },
      cf:{
        name:$scope.artwork.cf,
        value:$scope.artwork.cf ? $("select[name='cf']").find("option:selected").text() : ''
      },
      stock: {
        status: $scope.artwork.stockStatus,
        total: $scope.artwork.total,
        bookTotal: $scope.artwork.bookTotal,
        bookDay: $scope.artwork.bookDay,
        salesCount: $scope.artwork.salesCount
      },
      deliveryDays: $scope.artwork.deliveryDays,
      sellPoint: $scope.artwork.sellpoint,
      buyPrice: $scope.artwork.realCost,
      videos: $scope.videos,
      relates: $rootScope.selectedProducts,
      score: $scope.artwork.score,
      level: $scope.artwork.level,
      widht: $scope.artwork.width,
      long_: $scope.artwork.height,
      unit: $scope.artwork.unit,
      weight: weight,
      user:{
        id:$scope.currentUser.userId,
        name:$scope.currentUser.userName
      },
      wxicon: $scope.artwork.wxicon,
      pictures:$scope.artwork.pictures,
      content:Yihu.util.replaceLazyHtml($scope.artwork.contentBody)
    };
    if($scope.artwork.childCategory){
      artworkForm.artworkCategory.name = $scope.artwork.childCategory;
      artworkForm.artworkCategory.value = $("select[name='childCategory']").find("option:selected").text();
    }
    if($scope.artwork.sunCategory){
      artworkForm.artworkCategory.children = {
        name: $scope.artwork.sunCategory,
        value: $("select[name='sunCategory']").find("option:selected").text()
      };
    }
    if($scope.artwork.childBrand){
      artworkForm.brand.name = $scope.artwork.childBrand;
      artworkForm.brand.value = $("select[name='childBrand']").find("option:selected").text();
    }
    if($scope.artwork.sunBrand){
      artworkForm.brand.children = {
        name: $scope.artwork.sunBrand,
        value: $("select[name='sunBrand']").find("option:selected").text()
      };
    }
    if ($scope.hasParameters) {
      var params = {};
      $scope.parameters.forEach(function(item) {
        if (item.key) {
          params[item.propertyName] = {text: item.value, value: item.key};
        }
      });
      artworkForm.parameter = params;
    }
    ArtworkService.create({}, artworkForm, function(){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditProductCtrl', function($scope, $state, $timeout, Artwork, ArtworkService, Upload, $rootScope, Unsaved, BasicService, myModal, FileManagerService, DataDictService, WeixinService){
  $scope.ProductForm = {
    title:"更新艺术品"
  };  

  $scope.artwork = Artwork || {};
  $scope.videos = [{type: '', url: ''}];
  $rootScope.multiple = true;
  $scope.artwork.discountRate = 0.3;
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.artwork.name, width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.artwork.pictures.splice(i, 1);
      }
    });
  };

  var watcher = $scope.$watch("artwork", function(newVal, oldVal){
    if(newVal){
      watcher();
      init();

      $timeout(function(){
        if(Unsaved.content){
          $scope.artwork.content = Unsaved.content;
        }
        $scope.artwork.content = Yihu.util.restoreRawHtml($scope.artwork.content);
        $scope.artwork.status = $scope.artwork.commodityStates && $scope.artwork.commodityStates.id+'';
        $scope.artwork.stockStates = $scope.artwork.stock && $scope.artwork.stock.status + '';
        $scope.artwork.total = $scope.artwork.stock && $scope.artwork.stock.total || 0;
        $scope.artwork.bookDay = $scope.artwork.stock && $scope.artwork.stock.bookDay || 0;
        $scope.artwork.bookTotal = $scope.artwork.stock && $scope.artwork.stock.bookTotal || 0;
        $scope.artwork.salesCount = $scope.artwork.stock && $scope.artwork.stock.salesCount || 0;
        $scope.selectedTags = ($scope.artwork.keyword && $scope.artwork.keyword.join(' ')) || "";
        if(Artwork.isRecommend===1){
          $scope.artwork.isRecommend = true;
        }
        if(Artwork.useCoupon===1){
          $scope.artwork.useCoupon = true;
        }
        $scope.artwork.contentId = $scope.artwork.contentId;
        $scope.artwork.discountRate = 0.3;
        if (Artwork.wxicon) {
          $scope.artwork.wxiconUrl = Yihu.util.setContext($scope.downloadUrl, Artwork.wxicon+"?w=80");
        }
        if (Artwork.videos && Artwork.videos.length) {
          $scope.videos = Artwork.videos;
        }
        if (Artwork.relates && Artwork.relates.length) {
          $rootScope.selectedProducts = Artwork.relates;
        } else {
          $rootScope.selectedProducts = [];
        }
        if($scope.artwork.pictures && $scope.artwork.pictures.length){
          for(var i=0; i<$scope.artwork.pictures.length; i++){
            var p = $scope.artwork.pictures[i];
            var pid = $scope.artwork.pictures[i].id;
            $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: p.width, height: p.height});
          }
        }else{
          $scope.artwork.pictures = [];
        }
        $scope.init();
      }, 50);
    }
  });
  $scope.loadParams = function(catName, noAction){
    DataDictService.getChildren({
      parentPath: 'cms/product/category/' + catName
    }, function(data){
      if (data.childrens && data.childrens.length) {
        $scope.parameters = data.childrens;
        $scope.parameters.forEach(function(item) {
          if (item.css === 'textarea') {
            item.key = item.desc;
          }
        });
        $scope.hasParameters = true;
      } else if (!noAction){
        $scope.hasParameters = false;
      }
    });
  };

  $scope.addVideo = function(){
    $scope.videos.push({type: '', url: ''});
  };
  $scope.removeVideo = function(index) {
    if (index && $scope.videos.length > index) {
      $scope.videos.splice(index, 1);
    }
  };

  $scope.loadYearOptions = function(){
    DataDictService.getChildren({
      parentPath: 'cms/basedata/tea/year'
    }, function(data){
      $scope.artwork.yearList = data.childrens;
    });
  };
  $scope.loadQualityOptions = function(){
    DataDictService.getChildren({
      parentPath: 'cms/basedata/tea/quality'
    }, function(data){
      $scope.artwork.qualityList = data.childrens;
    });
  };
  $scope.loadCfOptions = function(){
    DataDictService.getChildren({
      parentPath: 'cms/basedata/tea/cf'
    }, function(data){
      $scope.artwork.cfList = data.childrens;
    });
  };
  $scope.loadVideoTypes = function(){
    DataDictService.getChildren({
      parentPath: 'cms/config/videotype'
    }, function(data){
      $scope.videoTypes = data.childrens || [];
    });
  };
  function initData() {
    $scope.loadYearOptions();
    $scope.loadQualityOptions();
    $scope.loadCfOptions();
    $scope.loadVideoTypes();
  }

  //初始化数据
  $scope.init = function(){
    var type = $scope.artwork.artworkType && $scope.artwork.artworkType.name;
    $scope.artwork.type = $scope.artwork.artworkType && $scope.artwork.artworkType.name;
    var cat = $scope.artwork.artworkCategory.parent && $scope.artwork.artworkCategory.parent.name;
    var subCat = $scope.artwork.artworkCategory.name;
    var brand = $scope.artwork.brand && $scope.artwork.brand.parent && $scope.artwork.brand.parent.name;
    var childbrand = $scope.artwork.brand && $scope.artwork.brand.name;

    BasicService.getArtworkCategory({ type: type }, function(data){
      // $scope.artwork.categoryList = data && data.childrens;
      $scope.artwork.categorys = data && data.childrens || [];

      angular.forEach($scope.artwork.categorys, function(item, idx){
        if(item.propertyName == cat) {
          $scope.artwork.childCategoryList = item.childrens || [];

          angular.forEach($scope.artwork.childCategoryList, function(node){
            if(node.propertyName == subCat) {
              $scope.artwork.sunCategoryList = node.childrens || [];
            }
          });

        }
        if (item.propertyName === 'brand') {
          $scope.artwork.brands = item.childrens || [];
          angular.forEach($scope.artwork.brands, function(node){
            if(node.propertyName == brand) {
              $scope.artwork.childBrandList = node.childrens || [];
              angular.forEach($scope.artwork.childBrandList, function(o){
                if(o.propertyName == childbrand) {
                  $scope.artwork.sunBrandList = o.childrens || [];
                }
              });
            }
          });
          $scope.artwork.categorys.splice(idx, 1);
        }
      });
    });
    if (subCat) {
      $scope.loadParams(cat + "_" + subCat, true);
    }
    $scope.loadParams(cat);
    initData();

    if(type === 'artwork'){
      $(".artist").show();
      $(".theme").show();
      $(".scene").show();
      $(".copyer").show();
      $(".tea").hide();
      $scope.getArtworkTheme(type); 
      $scope.getArtworkScene(type);
      BasicService.getArtist({type: type}, function(data){
        $scope.artwork.artistList = data && data.childrens;
      });
    }else{
      $(".artist").hide();
      $(".theme").hide();
      $(".scene").hide();
      $(".copyer").hide();
      $(".tea").show();
      $scope.artwork.artistList = [];
    }

    $timeout(function(){
      $scope.artwork.category = $scope.artwork.artworkCategory.parent.name;
      $scope.artwork.childCategory = $scope.artwork.artworkCategory.name;
      $scope.artwork.sunCategory = $scope.artwork.artworkCategory.children && $scope.artwork.artworkCategory.children.name;
      $scope.artwork.brandName = $scope.artwork.brand && $scope.artwork.brand.parent && $scope.artwork.brand.parent.name;
      $scope.artwork.childBrand = $scope.artwork.brand && $scope.artwork.brand.name;
      $scope.artwork.sunBrand = $scope.artwork.brand && $scope.artwork.brand.children && $scope.artwork.brand.children.name;
      $scope.artwork.author = $scope.artwork.artworkAuthor.name;
      $scope.artwork.newScene = $scope.artwork.scene.name;
      $scope.artwork.newSubject = $scope.artwork.subject.name;
      $scope.artwork.newYear = $scope.artwork.year && $scope.artwork.year.name || '';
      $scope.artwork.newQuality = $scope.artwork.quality && $scope.artwork.quality.name || '';
      $scope.artwork.newCf = $scope.artwork.cf && $scope.artwork.cf.name || '';

      if ($scope.artwork.parameter) {
        $scope.hasParameters = true;
        var params = $scope.parameters;
        params.forEach(function(value, key){
          var item = params[key];
          if ($scope.artwork.parameter[item.propertyName]) {
            item.key = $scope.artwork.parameter[item.propertyName] && $scope.artwork.parameter[item.propertyName].value;
          }
        });
      } else {
        $scope.hasParameters = false;
      }
    }, 500);
  };

  $scope.filterChildCategory = function() {
    $scope.loadParams($scope.artwork.category);
    $scope.artwork.childCategoryList = [];
    $scope.artwork.sunCategoryList = [];
    $scope.artwork.childCategory = '';
    $scope.artwork.sunCategory = '';
    angular.forEach($scope.artwork.categorys, function(item){
      if(item.propertyName == $scope.artwork.category) {
        $scope.artwork.childCategoryList = item.childrens || [];
      }
    });
  };

  $scope.filterSunCategory = function() {
    $scope.loadParams($scope.artwork.category + '_' + $scope.artwork.childCategory, true);
    $scope.artwork.sunCategoryList = [];
    $scope.artwork.sunCategory = '';
    angular.forEach($scope.artwork.childCategoryList, function(item){
      if(item.propertyName == $scope.artwork.childCategory) {
        $scope.artwork.sunCategoryList = item.childrens || [];
      }
    });
  };

  $scope.filterChildBrand = function() {
    $scope.artwork.childBrandList = [];
    $scope.artwork.childBrand = '';
    $scope.artwork.sunBrandList = [];
    $scope.artwork.sunBrand = '';
    angular.forEach($scope.artwork.brands, function(item){
      if(item.propertyName == $scope.artwork.brandName) {
        $scope.artwork.childBrandList = item.childrens || [];
      }
    });
  };
  $scope.filterSunBrand = function() {
    $scope.artwork.sunBrandList = [];
    $scope.artwork.sunBrand = '';
    angular.forEach($scope.artwork.childBrandList, function(item){
      if(item.propertyName == $scope.artwork.childBrand) {
        $scope.artwork.sunBrandList = item.childrens || [];
      }
    });
  };

  $scope.loadArtist = function(){
    $("select[name='subCategory']").addClass("hide");
    $scope.artwork.subCategoryList = [];
    $scope.artwork.subCategory = "";

    var key = $("select[name='type']").find("option:selected").val();
    if(!key){
      return;
    }

    //加载商品类型
    BasicService.getArtworkCategory({ type: key }, function(data){
      $scope.artwork.categoryList = data && data.childrens;
    });

    //加载商品艺术家, 雅集没有艺术家
    if(key === 'artwork'){
      $(".artist").show();
      $scope.getArtworkTheme(key); 
      $scope.getArtworkScene(key);
      BasicService.getArtist({type: key}, function(data){
        $scope.artwork.artistList = data && data.childrens;
      });
    }else{
      $(".artist").hide();
      $scope.artwork.artistList = [];
    }
  };

  $scope.loadSubCategory = function(){
    var type = $("select[name='type']").find("option:selected").val();
    var cat = $("select[name='category']").find("option:selected").val();
    var children = $("select[name='category']").find("option:selected").attr("children");
    if(!type || !cat || children == '0'){
      $("select[name='subCategory']").addClass("hide");
       $scope.artwork.subCategoryList = [];
       $scope.artwork.subCategory = "";
      return;
    }

    //加载商品子类型
    BasicService.getArtworkSubCategory({ type: type, category: cat}, function(data){
      var list = data && data.childrens;
      if(list && list.length){
        $("select[name='subCategory']").removeClass("hide").show();
        $scope.artwork.subCategoryList = list;
      }else{
        $("select[name='subCategory']").hide();
      }
    });
  };

  $scope.getArtworkTheme = function(type){
    $scope.artwork.subjectList = [];
    $scope.artwork.newSubject = "";
    BasicService.getArtworkTheme({type: type}, function(data){
      var list = data && data.childrens;
      if(list && list.length){
        $("." + data.propertyName).show();
        $scope.artwork.subjectList = list;
      }else{
        $("." + data.propertyName).hide();
      }
    }, function(){
      $(".theme").hide();
    });
  };

  $scope.getArtworkScene = function(type){
    $scope.artwork.sceneList = [];
    $scope.artwork.newScene = "";
    BasicService.getArtworkScene({type: type}, function(data){
      var list = data && data.childrens;
      if(list && list.length){
        $("." + data.propertyName).show();
        $scope.artwork.sceneList = list;
      }else{
        $("." + data.propertyName).hide();
      }
    }, function(){
      $(".scene").hide();
    });
  };

  // upload on files select or drop
  $scope.upload  = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    if (files && files.length) {
      $scope.showDialog = true;
      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            uploadedCallback(fileItem.fileName, fileItem);
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.artwork.pictures.push({
                id: data.id, 
                width: data.width,
                height: data.height,
                thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
                thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };

  function uploadedCallback(fileName, fileItem){
    var form = {
      path: '/product/默认库', 
      fileName: fileName,
      fileType: guessFileType(fileName),
      picture: {
        width: fileItem.width,
        height: fileItem.height,
        thWidth: { width: fileItem.thWidth && fileItem.thWidth.width, height: fileItem.thWidth && fileItem.thWidth.height},
        thHeight: { width: fileItem.thHeight && fileItem.thHeight.width, height: fileItem.thHeight && fileItem.thHeight.height},
        id: fileItem.id
      }
    };

    FileManagerService.mkdir({}, form, function(data){
      console.log(data);
    });
  }

  $scope.uploadPic = function (file) {
    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      if(data.code===0){
        uploadedCallback(data.fileName, data);
        $timeout(function(){
          $scope.artwork.wxiconUrl = data.url+"?w=80";
          $scope.artwork.wxicon = data.id;
        });
      }
    }, function (resp) {
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progressPercentage + '% ');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=150"),width: width, height: height});
            $scope.artwork.pictures.push({ id: id, width: width, height: height, 
              thWidth: { width: box.data("thwidthWidth") || "", height: box.data("thwidthHeight") || ""}, 
              thHeight: { width: box.data("thheightWidth") || "", height: box.data("thheightHeight") || ""} 
            });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = "/product";
  function getList(){
    var opts = {
      order:"name",
      desc:1,
      // type:"image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.hasNotify = false;
  $scope.sendNotify = function() {
    var ids = $scope.artwork.stock && $scope.artwork.stock.outStockUsers || [];
    if (ids.length === 0) {
      return;
    }
    var name = $scope.artwork.name;
    WeixinService.arrivalNotify({
      title: '预定商品已到货',
      date: moment(new Date(new Date().getTime() + 10000)).format("YYYY-MM-DD HH:mm"),
      content: name + '到货了! ',
      remark: '您预定的' + name + '到货了! 快进来看看吧!',
      openids: $scope.artwork.stock.outStockUsers,
      url: '/#/good/' + $scope.artwork.id
    }, function(data) {
      $scope.hasNotify = true;
    });
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };
  $scope.removeProduct = function(idx) {
    if ($rootScope.selectedProducts && $rootScope.selectedProducts.length > idx) {
      $rootScope.selectedProducts.splice(idx, 1);
    }
  };
  $scope.cleanProducts = function() {
    $rootScope.selectedProducts = [];
    $rootScope.multiSelectProducts = [];
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.multiple = false;
    $rootScope.multiSelectProducts = [];
    $rootScope.selectedProducts = [];
  });

  $scope.submitForm = function(){
    var weight = 0;
    $(".form-tags>span").map(function(){ 
      weight += $(this).data("weight") || 1;
    });
    if ($scope.videos.length === 1 && $scope.videos[0].url === '') {
      $scope.videos = [];
    }
    var artworkForm = {
      name: $scope.artwork.name,
      costPrice: $scope.artwork.costPrice,
      markPrice: $scope.artwork.markPrice,
      activityPrice: $scope.artwork.activityPrice,
      keyword: ($scope.selectedTags && $scope.selectedTags.split(" ")) || [],
      like: $scope.artwork.like,
      pv: $scope.artwork.pv,
      sorts: $scope.artwork.sorts,
      isRecommend: $("input[name='isRecommend']").prop('checked') ? 1 : 0,
      useCoupon: $("input[name='useCoupon']").prop('checked') ? 1 : 0,
      couponPercent: $("input[name='useCoupon']").prop('checked') && $scope.artwork.couponPercent || 0,
      storage: $("input[name='storage']").prop('checked'),
      years: $("input[name='storage']").prop('checked') ? $scope.artwork.years : 0,
      storeFee: $("input[name='storage']").prop('checked') ? $scope.artwork.storeFee : 0,
      videoUrl: $scope.artwork.videoUrl || '',
      commodityStates:{
        id: $scope.artwork.status,
        name: $("select[name='status']").find("option:selected").text()
      },
      artworkAuthor:{
        name: $scope.artwork.author,
        value: $("select[name='author']").find("option:selected").text()
      },
      artworkCategory:{
        name: '',
        value: '',
        parent: {
          name: $scope.artwork.category,
          value: $("select[name='category']").find("option:selected").text()
        }
      },
      artworkType:{
        name:$scope.artwork.type,
        value:$("select[name='type']").find("option:selected").text()
      },
      brand:{
        name: '',
        value: '',
        parent: {
          name: $scope.artwork.brandName,
          value: $("select[name='brandName']").find("option:selected").text()
        }
      },
      subject:{
        name:$scope.artwork.newSubject,
        value:$("select[name='newSubject']").find("option:selected").text()
      },
      scene:{
        name:$scope.artwork.newScene,
        value:$("select[name='newScene']").find("option:selected").text()
      },
      year:{
        name:$scope.artwork.newYear,
        value:$scope.artwork.newYear ? $("select[name='year']").find("option:selected").text() : ''
      },
      quality:{
        name:$scope.artwork.newQuality,
        value:$scope.artwork.newQuality ? $("select[name='quality']").find("option:selected").text() : ''
      },
      cf:{
        name:$scope.artwork.newCf,
        value:$scope.artwork.newCf ? $("select[name='cf']").find("option:selected").text() : ''
      },
      stock: {
        status: $scope.artwork.stockStates,
        total: $scope.artwork.total,
        bookTotal: $scope.artwork.bookTotal,
        bookDay: $scope.artwork.bookDay,
        salesCount: $scope.artwork.salesCount
      },
      videos: $scope.videos,
      relates: $rootScope.selectedProducts,
      deliveryDays: $scope.artwork.deliveryDays,
      sellPoint: $scope.artwork.sellPoint,
      buyPrice: $scope.artwork.buyPrice,
      score: $scope.artwork.score,
      level: $scope.artwork.level,
      widht: $scope.artwork.widht,
      long_: $scope.artwork.long_,
      unit: $scope.artwork.unit,
      weight: weight,
      user:{
        id:$scope.currentUser.userId,
        name:$scope.currentUser.userName
      },
      id: $state.params.id,
      wxicon: $scope.artwork.wxicon,
      pictures:$scope.artwork.pictures,
      content:Yihu.util.replaceLazyHtml($scope.artwork.contentBody),
      contentId:$scope.artwork.contentId
    };
    if($scope.artwork.childCategory){
      artworkForm.artworkCategory.name = $scope.artwork.childCategory;
      artworkForm.artworkCategory.value = $("select[name='childCategory']").find("option:selected").text();
    }
    if($scope.artwork.sunCategory){
      artworkForm.artworkCategory.children = {
        name: $scope.artwork.sunCategory,
        value: $("select[name='sunCategory']").find("option:selected").text()
      };
    }
    if($scope.artwork.childBrand){
      artworkForm.brand.name = $scope.artwork.childBrand;
      artworkForm.brand.value = $("select[name='childBrand']").find("option:selected").text();
    }
    if($scope.artwork.sunBrand){
      artworkForm.brand.children = {
        name: $scope.artwork.sunBrand,
        value: $("select[name='sunBrand']").find("option:selected").text()
      };
    }
    if ($scope.hasParameters) {
      var params = {};
      $scope.parameters.forEach(function(item) {
        if (item.key) {
          params[item.propertyName] = {text: item.value, value: item.key};
        }
      });
      artworkForm.parameter = params;
    }
    ArtworkService.update({}, artworkForm, function(){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('ProductCommentsCtrl', function($scope, $state, uiGridConstants, myModal,CommentService, $rootScope){
  $scope.comment = {};
  $scope.Form = {
    title:'评论管理'
  };

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };

  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });

    init();
  };
   
  $scope.gridOptions.columnDefs = [{
      field: 'from.userName',
      displayName: '评论人',      
      cellTemplate: '<span><span ng-if="!COL_FIELD">匿名</span><span ng-if="COL_FIELD">{{COL_FIELD}}</span></span>',
      width:160
    },{
      field: 'content',
      displayName: '评论内容',
    }, {
      field: 'createdAt',
      displayName: '发布时间',      
      type: 'date',
      width:140
    // }, {
    //   field: 'reply.from.userName',
    //   displayName: '回复人',      
    //   width:160  
    // }, {
    //   field: 'reply.content',
    //   displayName: '回复内容',    
    // }, {
    //   field: 'reply.createdAt',
    //   displayName: '回复时间',      
    //   type: 'date',
    //   width:140
    }, {
      field: 'status',
      displayName: '审批状态',
      width:120,
      cellFilter:'commentStatus'
    }, {
      field: 'reply.replyId',
      displayName: '回复ID',
      visible: false
    }, {
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/products/'+ $state.params.id+'/comments/{{COL_FIELD}}">查看回复</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="btn-small" href="#/products/'+ $state.params.id+'/comments/{{COL_FIELD}}/reply">直接回复</a>',
      enableFiltering: false
    }
  ];

  var getPage = function() {
    CommentService.getList({
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize,
      productId: $state.params.id || "",
      from: 1
    }, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var jsonData = data.comments || [];
      angular.forEach(jsonData, function(item){
        item.createdAt = moment(item.createdAt).format("YYYY-MM-DD HH:mm");
      });
      $scope.gridOptions.data = jsonData;
    });
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if($rootScope.nestedAnimated){
      $rootScope.nestedAnimated = false;
      $rootScope.currentAnimated = false;
    }else if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  $scope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $rootScope.nestedAnimated = true;
    $state.go('^');
  };

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //通过审批
  $scope.approve = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;
        var count = (row.entity.reply && row.entity.reply.replyId) || 0;
        var form = {
          id: id, 
          count: count
        };
        CommentService.approve({}, form, function(data){
          if(data.result === 0){
            getPage();
          }
        });
      });
    }
  };

  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        CommentService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };

})
.controller('AddCommentCtrl', function($scope, $state, CommentService, $rootScope, $timeout, myModal, FileManagerService){
  $scope.Form = {
    title:"新增商品评论"
  };

  $scope.comment = { score: 5 };
  $scope.comment.pictures = [];
  var icons = $scope.icons = [];
  $scope.images = [];

  $timeout(function() {
    init();
  },50);

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: '评论图',width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.comment.pictures.splice(i, 1);
      }
    });
  };

  // upload on files select or drop
  $scope.upload  = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };

    if (files && files.length) {
      $scope.showDialog = true;

      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.comment.pictures.push({
                pid: data.id
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };

  //初始化
  function init(){ 
    getList();
    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=150"),width: width, height: height});
            $scope.comment.pictures.push({ pid: id });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = "/product";
  function getList(){
    var opts = {
      order:"name",
      desc:1,
      // type:"image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
  });

  $scope.submitForm = function(){
    var form = {
      content: $scope.comment.content,
      from: {
        userId: -999,
        userName: $scope.comment.userName
      },
      product: {
        pid: $state.params.id || ''
      },
      pictures: $scope.comment.pictures,
      score: $scope.comment.score
    };
    CommentService.create({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditCommentCtrl', function($scope, $state, CommentService, $rootScope, $timeout, Comment, FileManagerService, myModal){
  $scope.Form = {
    title:"更新商品评论"
  };
  $scope.comment = Comment || {};
  var watcher = $scope.$watch("comment.content", function(newValue, oldValue){
    watcher();
    init();

    $timeout(function(){
      $scope.comment = Comment || {};
      $scope.comment.userName = $scope.comment.from && $scope.comment.from.userName;
      if($scope.comment.pictures){
        for(var i=0; i<$scope.comment.pictures.length; i++){
          var p = $scope.comment.pictures[i];
          var pid = $scope.comment.pictures[i].pid;
          $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        }
      }else{
        $scope.comment.pictures = [];
      }
    }, 50);
  });

  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: '评论图',width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.comment.pictures.splice(i, 1);
      }
    });
  };

  // upload on files select or drop
  $scope.upload  = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };

    if (files && files.length) {
      $scope.showDialog = true;

      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.comment.pictures.push({
                pid: data.id
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };

  //初始化
  function init(){ 
    getList();
    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=150"),width: width, height: height});
            $scope.comment.pictures.push({ pid: id });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = "/product";
  function getList(){
    var opts = {
      order:"name",
      desc:1,
      // type:"image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
  });

  $scope.submitForm = function(){
    var form = {
      content: $scope.comment.content,
      from: {
        userId: -999,
        userName: $scope.comment.userName
      },
      product: {
        pid: $state.params.id || ''
      },
      pictures: $scope.comment.pictures,
      score: $scope.comment.score
    };
    CommentService.update({id: $state.params.cid}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  $rootScope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $state.go('^');
  };

})
.controller('CommentReplyListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, CommentService, $timeout, $rootScope){
  $scope.Form = {
    title:'回复评论管理'
  };

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  $scope.comment = {};
  $timeout(function(){
    init();
  }, 50);

  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };

  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
  };
   
  $scope.gridOptions.columnDefs = [{
      field: 'reply.from.userName',
      displayName: '回复人',      
      cellTemplate: '<span><span ng-if="!COL_FIELD">匿名</span><span ng-if="COL_FIELD">{{COL_FIELD}}</span></span>',
      width:160  
    }, {
      field: 'reply.content',
      displayName: '回复内容',    
    }, {
      field: 'reply.createdAt',
      displayName: '回复时间',      
      type: 'date',
      width:140
    }, {
      field: 'status',
      displayName: '审批状态',
      width:120,
      cellFilter:'commentStatus'
    }, {
      field: 'reply.replyId',
      displayName: '回复ID',
      visible: false
    }
  ];

  var getPage = function() {
    var comments = [];
    CommentService.findOne({id:$stateParams.cid}, function(data){
      if(data.replys && data.replys.length){
        $scope.gridOptions.totalItems = data.replys.length;
        for(var i=0, len=data.replys.length; i<len; i++){
          var reply = data.replys[i];
          comments.push({
            id: data.id,
            product: data.product,
            from: data.from,
            content: data.content,
            createdAt: data.createdAt,
            reply: {
              from: reply.from,
              to: reply.to,
              content: reply.content,
              replyId: reply.replyId,
              createdAt: moment(reply.createdAt).format("YYYY-MM-DD HH:mm")
            },
            status: reply.status
          });
        }
      }else{
        $scope.gridOptions.totalItems = 1;
      }
      $scope.gridOptions.data = comments;
    });
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if($rootScope.nestedAnimated){
      $rootScope.nestedAnimated = false;
      $rootScope.currentAnimated = false;
    }else if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  $scope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $rootScope.nestedAnimated = true;
    $state.go('^');
  };

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //通过审批
  $scope.approve = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;
        var count = (row.entity.reply && row.entity.reply.replyId) || 0;
        var form = {
          id: id, 
          count: count
        };
        CommentService.approve({}, form, function(data){
          if(data.result === 0){
            getPage();
          }
        });
      });
    }
  };

  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        CommentService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };

})
.controller('AddCommentReplyCtrl', function($scope, $state, CommentService, Comment, $rootScope, $timeout){
  $scope.Form = {
    title:"新增评论回复"
  };

  $scope.reply = {};
  $scope.comment = Comment || {};
  var watcher = $scope.$watch("comment.content", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.comment = Comment || {};
    }, 50);
  });

  $scope.submitForm = function(){
    var comment = {
      product: { pid: $state.params.id }, 
      reply: {
        from: { 
          userId: -1, 
          userName: 'yihuyixi'
        },
        to: {
          userId: $scope.comment.from.userId, 
          userName: $scope.comment.from.userName
        },
        content: $scope.reply.content
      },
      count: $scope.comment.count,
      id: $state.params.cid
    };
    CommentService.create({}, comment, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('QrcodeCtrl', function($scope, $state, uiGridConstants, myModal,CouponService, $rootScope, Config){
  $scope.Form = {
    title:'生成产品二维码'
  };
  $scope.qrcode = {};

  var watcher = $rootScope.$watch("choosedProduct", function(newValue, oldValue){
    var product = $rootScope.choosedProduct;
    $scope.qrcode.artworkId = product.id || '';
  });

  $scope.submitForm = function(){
    if($scope.qrcode.artworkId) {
      $scope.downloadQrcode = Config.profiles[Config.env].context + '/qrcode/artwork?aid=' + $scope.qrcode.artworkId;
    }
  };

  $scope.cleanup = function(){
    $scope.qrcode.artworkId = '';
    $scope.downloadQrcode = '';
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $rootScope.choosedProduct = {};
  });

});

/**
 * 衍生品管理模块
 * @type {[type]}
 */
var derivativiesListModule = angular.module("DerivativiesListModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns']);
derivativiesListModule.controller('DerivativiesListCtrl', function($scope, $state, uiGridConstants, myModal, Derivativies, DerivativiesService, $rootScope){
  $scope.derivatives = Derivativies || {};
  $scope.DerivativesForm = {
    title:'衍生品管理'
  };

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };

  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });

    init();
  };
   
  $scope.gridOptions.columnDefs = [{
      field: 'name',
      displayName: '商品名称',
      width:260
    },{
      field: 'derivativesAuthor.name',
      displayName: '艺术家',
      width:100
    },{
      field: 'derivativesCategory.name',
      displayName: '商品类别',
      width:90
    },{
      field: 'baseCommodityCategory.name',
      displayName: '商品分类',
      width:90
    },{
      field: 'price',
      displayName: '价格',
      type:'number',
      width:80
    },{
      field: 'createTime',
      displayName: '发布日期',
      type: 'date',
      width:140
    }, {
      field: 'material.name',
      displayName: '材质',      
      width:80
    }, {
      field: 'putOnShelvesTime',
      displayName: '上架时间',      
      type: 'date',
      width:140
    }, {
      field: 'commodityStates.name',
      displayName: '状态',
      width:80
    }, {
      field: 'isRecommend',
      displayName: '推荐',
      width:80
    }, {
      field: 'pv',
      displayName: 'PV',
      width:80
    }, {
      field: 'sorts',
      displayName: '排序',
      width:80
    }, {
      field: 'like',
      displayName: '收藏数',
      width:80
    }, {
      name: '_id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/products/derivatives/edit/{{COL_FIELD}}">修改</a>',
      enableFiltering: false
    }
  ];

  var getPage = function() {
    var form = {
      name: $scope.derivatives.name,
      commodityStatesId: $scope.derivatives.states||0,
      materialName: $scope.derivatives.material,
      artworkCategoryId: $scope.derivatives.category||0,
      artworkAuthorName: $scope.derivatives.author,
      price:{
        minPrices:$scope.derivatives.minPrice, 
        maxPrices:$scope.derivatives.maxPrice
      },
      pst:{
        beginPutOnShelvesTime:$("#beginShelvesTime").val(),
        endPutOnShelvesTime:$("#endShelvesTime").val()
      }
    };

    DerivativiesService.getList({
      curPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize,
      commodityCategoryId: $scope.derivatives.commodityCategoryId || $state.params.productId
    }, form, function(data){
      $scope.gridOptions.totalItems = data.total || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var artworkData = data.info || [];
      
      angular.forEach(artworkData, function(item){
        item.putOnShelvesTime = moment(item.putOnShelvesTime).format("YYYY-MM-DD HH:mm");
        item.createTime = moment(item.createTime).format("YYYY-MM-DD HH:mm");
      });
      $scope.gridOptions.data = artworkData;
    });
  };

  //初始化
  function init(){
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if($rootScope.nestedAnimated){
      $rootScope.nestedAnimated = false;
      $rootScope.currentAnimated = false;
    }else if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  $scope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $rootScope.nestedAnimated = true;
    $state.go('^');
  };

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //删除
  $scope.remove = function(){
    $("#myModal").remove();

    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        DerivativiesService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };

})
.controller('AddDerivativiesCtrl', function($scope, $state, $timeout, Upload, Derivativies, DerivativiesService, $rootScope, Unsaved){
  $scope.ProductForm = {
    title:"新增衍生品"
  };
  $scope.derivatives = Derivativies || {};
  $scope.selectedTags = "";

  var watcher = $scope.$watch("derivatives", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        $scope.derivatives.id = Unsaved.id;
        $scope.derivatives.content = Unsaved.content;
      }, 50);
    }

  });

  $scope.derivatives.pictures = [];
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.derivatives.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.derivatives.pictures.splice(i, 1);
      }
    });
  };

  // upload on files select or drop
  $scope.upload  = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    if (files && files.length) {
      $scope.showDialog = true;
      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.derivatives.pictures.push({
                id: data.id, 
                width: data.width,
                height: data.height,
                thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
                thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };

  $scope.submitForm = function(){
    var form = {
      name: $scope.derivatives.name,
      price: $scope.derivatives.price,
      keyword: ($scope.selectedTags && $scope.selectedTags.split(" ")) || [],
      like: $scope.derivatives.like,
      pv: $scope.derivatives.pv,
      sorts: $scope.derivatives.sorts,
      isRecommend: $("input[name='isRecommend']").prop('checked') ? 1 : 0,
      commodityStates:{
        id: $scope.derivatives.commodityStates,
        name: $("select[name='commodityStates']").find("option:selected").text()
      },
      derivativesAuthor:{
        id: $scope.derivatives.derivativesAuthor,
        name: $("select[name='derivativesAuthor']").find("option:selected").text()
      },
      derivativesCategory:{
        id: $scope.derivatives.derivativesCategory,
        name: $("select[name='derivativesCategory']").find("option:selected").text()
      },
      baseCommodityCategory:{
        id:$scope.derivatives.baseCommodityCategory,
        name:$("select[name='baseCommodityCategory']").find("option:selected").text()
      },
      widht: $scope.derivatives.width,
      long_: $scope.derivatives.height,
      unit: $scope.derivatives.unit,
      material:{
        id:$scope.derivatives.material,
        name: $("select[name='material']").find("option:selected").text()
      },
      user:{        
        id:$scope.currentUser.userId,
        name:$scope.currentUser.userName
      },
      content: Yihu.util.replaceLazyHtml($scope.derivatives.contentBody),
      pictures: $scope.derivatives.pictures
    };

    DerivativiesService.create({}, form, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditDerivativiesCtrl', function($scope, $state, $timeout, Upload, Derivativies, DerivativiesService, $rootScope, Unsaved){
  $scope.ProductForm = {
    title:"更新衍生品"
  };

  $scope.derivatives = Derivativies || {};
  var watcher = $scope.$watch("derivatives.name", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        $scope.derivatives.content = Derivativies.content;
        if(Unsaved.content){
          $scope.derivatives.content = Unsaved.content;
        }

        $scope.derivatives.content = Yihu.util.restoreRawHtml($scope.derivatives.content);
        $scope.derivatives.derivativesCategory = $scope.derivatives.derivativesCategory.id+'';
        $scope.derivatives.derivativesAuthor = $scope.derivatives.derivativesAuthor.id+'';
        // $scope.derivatives.material = $scope.derivatives.material.id+'';
        $scope.derivatives.commodityStates = $scope.derivatives.commodityStates.id+'';
        $scope.derivatives.type = $scope.derivatives.baseCommodityCategory && $scope.derivatives.baseCommodityCategory.id+'';
        $scope.selectedTags = ($scope.derivatives.keyword && $scope.derivatives.keyword.join(' ')) || "";
        if(Derivativies.isRecommend===1){
          $scope.derivatives.isRecommend = true;
        }
        $scope.derivatives.contentId=$scope.derivatives.contentId;

        if($scope.derivatives.pictures){
          for(var i=0; i<$scope.derivatives.pictures.length; i++){
            var p = $scope.derivatives.pictures[i];
            var pid = $scope.derivatives.pictures[i].id;
            $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: p.width, height: p.height});
          }
        }else{
          $scope.derivatives.pictures = [];
        }
      }, 50);
    }
  });
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.derivatives.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.derivatives.pictures.splice(i, 1);
      }
    });
  };

  // upload on files select or drop
  $scope.upload  = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    if (files && files.length) {
      $scope.showDialog = true;

      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.derivatives.pictures.push({
                id: data.id, 
                width: data.width,
                height: data.height,
                thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
                thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };    

  $scope.submitForm = function(){
    var pictureUrls = [];
    if($scope.derivatives.pictures && $scope.derivatives.pictures.id){
      pictureUrls.push($scope.derivatives.pictures);
    }else{
      pictureUrls = $scope.derivatives.pictures;
    }

    var form = {
      name: $scope.derivatives.name,
      price: $scope.derivatives.price,
      keyword: ($scope.selectedTags && $scope.selectedTags.split(" ")) || [],
      like: $scope.derivatives.like,
      pv: $scope.derivatives.pv,
      sorts: $scope.derivatives.sorts,
      isRecommend: $("input[name='isRecommend']").prop('checked') ? 1 : 0,
      commodityStates:{
        id: $scope.derivatives.commodityStates,
        name: $("select[name='commodityStates']").find("option:selected").text()
      },
      derivativesAuthor:{
        id: $scope.derivatives.derivativesAuthor,
        name: $("select[name='derivativesAuthor']").find("option:selected").text()
      },
      derivativesCategory:{
        id: $scope.derivatives.derivativesCategory,
        name: $("select[name='derivativesCategory']").find("option:selected").text()
      },
      baseCommodityCategory:{
        id:$scope.derivatives.type,
        name:$("select[name='type']").find("option:selected").text()
      },
      widht: $scope.derivatives.widht,
      long_: $scope.derivatives.long_,
      unit: $scope.derivatives.unit,
      // material:{
      //   id:$scope.derivatives.material,
      //   name: $("select[name='material']").find("option:selected").text()
      // },
      user:{
        id:$scope.currentUser.userId,
        name:$scope.currentUser.userName
      },
      _id: $state.params.id,
      contentId:$scope.derivatives.contentId,
      content: Yihu.util.replaceLazyHtml($scope.derivatives.contentBody),
      pictures: $scope.derivatives.pictures
    };

    DerivativiesService.update({}, form, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})

/** 轮播广告管理 */
.controller('PosterListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, PosterService, $rootScope) {
  $scope.poster = {};
  $scope.PosterForm = {
    title:'轮播广告管理'
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    enableSorting: true,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'title',
      displayName: '广告标题',
      width:300
    }, {
      field: 'name',
      displayName: '轮播广告描述',
      width:300
    },{
      field: 'type',
      displayName: '类型',
      width:80
    },{
      field: 'url',
      displayName: '跳转地址',
      width:380
    },{
      field: 'sort',
      displayName: '排序',
      width:80
    },{
      field: 'creatAt',
      displayName: '创建时间',
      width:120
    }, {
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/poster/edit/{{COL_FIELD}}">修改</a>',
      enableFiltering: false
    }
  ];

  //分页查询
  var getPage = function() {
    var name = $scope.poster.name || '';

    PosterService.getList({ name: name }, function(data){
      var ads = data.posters || [];
      angular.forEach(ads, function(item){
        item.creatAt = moment(item.creatAt).format("YYYY-MM-DD HH:mm");
      });
      $scope.gridOptions.data = ads;
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if($rootScope.nestedAnimated){
      $rootScope.nestedAnimated = false;
      $rootScope.currentAnimated = false;
    }else if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;
 
        PosterService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  }; 

})
.controller('AddPosterCtrl', function($scope, $state, $timeout, PosterService, Upload, $rootScope,myModal, FileManagerService){
  $scope.PosterForm = {
    title:"新增轮播广告"
  };

  $scope.poster = {};
  $timeout(function(){
    init();
  });

  // upload on file select or drop
  $scope.upload  = function (file) {
    if(!file){
      return;
    }
    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      if(data.code===0){
        $timeout(function(){
          $scope.poster.icon = Yihu.util.setContext($scope.downloadUrl, data.id+"?w=990");
          $scope.poster.fileId = data.id;
        });
      }
    }, function (resp) {
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progressPercentage + '% ');
    });
  };

  $scope.submitForm = function(){
    var form = {
      name: $scope.poster.name,
      title: $scope.poster.title,
      type: $scope.poster.type,
      url: $scope.poster.url,
      fileId: $scope.poster.fileId,
      sort: $scope.poster.sort
    };

    PosterService.create(form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('只允许选择一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.poster.icon = Yihu.util.setContext($scope.downloadUrl, id+"?w=990");
            $scope.poster.fileId = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = "/banner";
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      // type: "image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
  });
})
.controller('EditPosterCtrl', function($scope, $state, $timeout, PosterService, $rootScope, Poster, Upload,myModal, FileManagerService){
  $scope.PosterForm = {
    title:"更新轮播广告"
  };

  $scope.poster = Poster || {};
  $scope.poster.icon = Yihu.util.setContext($scope.downloadUrl, Poster.fileId ? Poster.fileId+"?w=990": '');

  var watcher = $scope.$watch("poster.name", function(newVal, oldVal){
    if(newVal){
      watcher();
      init();

      $timeout(function(){
        $scope.poster = Poster;
        $scope.poster.icon = Yihu.util.setContext($scope.downloadUrl, Poster.fileId ? Poster.fileId+"?w=990": '');
      }, 50);
    }
  });

  // upload on file select or drop
  $scope.upload  = function (file) {
    if(file){
      return;
    }
    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      if(data.code===0){
        $timeout(function(){
          $scope.poster.icon = Yihu.util.setContext($scope.downloadUrl, data.id+"?w=990");
          $scope.poster.fileId = data.id;
        });
      }
    }, function (resp) {
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progressPercentage + '% ');
    });
  };

  $scope.submitForm = function(){
    var form = {
      name: $scope.poster.name,
      title: $scope.poster.title,
      type: $scope.poster.type,
      url: $scope.poster.url,
      fileId: $scope.poster.fileId,
      sort: $scope.poster.sort
    };

    PosterService.update({id: $state.params.id}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('只允许选择一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.poster.icon = Yihu.util.setContext($scope.downloadUrl, id+"?w=990");
            $scope.poster.fileId = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = "/banner";
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      // type: "image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
  });
});

/**
 * 评论模块列表
 * @type {[type]}
 */
var commentListModule = angular.module("CommentListModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ngFileUpload']); 
commentListModule.controller('CommentListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, $rootScope, CommentService) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'product.pid',
      displayName: '评论模块ID',
      width:220
    },{
      field: 'from.userName',
      displayName: '评论人',
      width:160
    },{
      field: 'content',
      displayName: '评论内容',
    }, {
      field: 'createdAt',
      displayName: '发布时间',      
      type: 'date',
      width:140
    }, {
      field: 'reply.from.userName',
      displayName: '回复人',    
      width:160  
    }, {
      field: 'reply.content',
      displayName: '回复内容',    
    }, {
      field: 'reply.createdAt',
      displayName: '回复时间',      
      type: 'date',
      width:140
    }, {
      field: 'status',
      displayName: '审批状态',
      width:120,
      cellFilter:'commentStatus'
    }, {
      field: 'reply.replyId',
      displayName: '回复ID',
      visible: false
      // cellTemplate: '<a class="btn-small" href="#/comment/edit/{{COL_FIELD}}">通过审批</a>&nbsp;&nbsp;',
      // enableFiltering: false
    }, {
      field: 'id',
      displayName: '操作',
      visible: false
      // cellTemplate: '<a class="btn-small" href="#/comment/edit/{{COL_FIELD}}">通过审批</a>&nbsp;&nbsp;',
      // enableFiltering: false
    }
  ];

  //分页查询
  var getPage = function() {
    var articleForm = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize      
    };
    CommentService.getList({}, articleForm, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var jsonData = data.comments || [];

      var comments = [];
      angular.forEach(jsonData, function(item){
        item.createdAt = moment(item.createdAt).format("YYYY-MM-DD HH:mm");
        comments.push(item);

        if(item.replys && item.replys.length){
          for(var i=0, len=item.replys.length; i<len; i++){
            var reply = item.replys[i];
            comments.push({
              id: item.id,
              product: item.product,
              from: item.from,
              content: item.content,
              createdAt: item.createdAt,
              reply: {
                from: reply.from,
                to: reply.to,
                content: reply.content,
                replyId: reply.replyId,
                createdAt: moment(reply.createdAt).format("YYYY-MM-DD HH:mm"),
              },
              status: reply.status
            });
          }
        }
      });
      $scope.gridOptions.data = comments;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){

    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //通过审批
  $scope.approve = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;
        var count = (row.entity.reply && row.entity.reply.replyId) || 0;
        var form = {
          id: id, 
          count: count
        };
        CommentService.approve({}, form, function(data){
          if(data.result === 0){
            getPage();
          }
        });
      });
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        CommentService.remove({
          id:id
        }, function(data){
          if(data.result === 0){
            getPage();
          }
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.filter('commentStatus', function(){
  var statusHash = {
    'AUDITED':'审批通过',
    'PENDINGAUDIT':'待审批'
  };
  return function(input){
    return statusHash[input];
  };
});

/**
 * 主题活动模块列表
 * @type {[type]}
 */
var activityListModule = angular.module("ActivityListModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ngFileUpload']); 
activityListModule.controller('ActivityListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, ActivityService, $rootScope) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'subject',
      displayName: '活动主题',
      width:280
    },{
      field: 'address',
      displayName: '活动地点',
      width:380
    },{
      field: 'startTime',
      displayName: '起止时间',
      cellTemplate: '<span>{{COL_FIELD}} ~ {{row.entity.endTime}}</span>',
      enableFiltering: false
    },{
      field: 'price',
      displayName: '活动费用'
    },{
      field: 'amount',
      displayName: '活动人数'
    },{
      field: 'sign_upCount',
      displayName: '已报名人数'
    },{
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/activity/edit/{{COL_FIELD}}">修改</a>',
      enableFiltering: false
    }
  ];

  $scope.activity = {};

  //分页查询
  var getPage = function() {
    var activityForm = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      startDate:$("#beginPublishTime").val(),
      endDate:$("#endPublishTime").val()
    };
    ActivityService.getList(activityForm, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      $scope.gridOptions.data = data.actvities || [];
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        ActivityService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.controller('AddActivityCtrl', function($scope, $state, $timeout, ActivityService, Upload, $rootScope, Unsaved,myModal, FileManagerService){
  $scope.ActivityForm = {
    title:"新增活动"
  };
  
  $scope.activity = {
    statusList: [{id:0,  name: "待发布"}, {id:1,  name: "进行中"}, {id:2,  name: "已结束"}],
    status: "0"
  };

  $timeout(function(){
    init();
  });

  var watcher = $scope.$watch("activity.subject", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        $scope.activity.desc = Unsaved.content;
      }, 50);
    }
  });

  $scope.activity.pictures = [];
  var icons = $scope.icons = [];
  $scope.images = [];
  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?h=180',''), title: $scope.activity.subject,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.activity.pictures.splice(i, 1);
      }
    });
  };

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.activity.pictures.push({
            id: data.id, 
            width: data.width,
            height: data.height,
            thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
            thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
          });
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var form = {
      subject:$scope.activity.subject,
      startTime:$("#startTime").val(),
      endTime:$("#endTime").val(),
      address:$scope.activity.address,
      price:$scope.activity.price,
      amount:$scope.activity.amount,
      status:$scope.activity.status,
      icons: $scope.activity.pictures,
      content:Yihu.util.replaceLazyHtml($scope.activity.contentBody),
      summary: $scope.activity.summary
    };

    ActivityService.create({}, form, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.activity.pictures.push({ id: id, width: width, height: height, 
              thWidth: { width: box.data("thwidthWidth") || "", height: box.data("thwidthHeight") || ""}, 
              thHeight: { width: box.data("thheightWidth") || "", height: box.data("thheightHeight") || ""} 
            });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      type: "image",
      path: "/activity"
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
  });
})
.controller('EditActivityCtrl', function($scope, $state, $timeout, Activity, ActivityService, Upload, $rootScope, Unsaved,myModal, FileManagerService){
  $scope.ActivityForm = {
    title:"更新活动"
  };
  $scope.activity = Activity || {};
  $scope.activity.statusList = [{id:0,  name: "待发布"}, {id:1,  name: "进行中"}, {id:2,  name: "已结束"}];
  var icons = $scope.icons = [];
  $scope.images = [];
  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?h=180',''), title: $scope.activity.subject,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.activity.icons.splice(i, 1);
      }
    });
  };

  var watcher = $scope.$watch("activity.subject", function(newVal, oldVal){
    if(newVal){
      watcher();
      init();

      $timeout(function(){
        $scope.activity.status = (Activity.status || 0)+'';

        if(Unsaved.content){
          $scope.activity.desc = Unsaved.content;
        }
        $scope.activity.desc = Yihu.util.restoreRawHtml($scope.activity.desc);
        if($scope.activity.icons){
          for(var i=0; i<$scope.activity.icons.length; i++){
            var p = $scope.activity.icons[i];
            var pid = $scope.activity.icons[i].id;
            $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?h=180"),width: p.width, height: p.height});
          }
        }else{
          $scope.activity.icons = [];
        }

      }, 50);
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.totalFiles){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.activity.icons.push({
            id: data.id, 
            width: data.width,
            height: data.height,
            thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
            thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
          });
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };
  
  $scope.submitForm = function(){
    var form = {
      subject:$scope.activity.subject,
      startTime:$("#startTime").val(),
      endTime:$("#endTime").val(),
      address:$scope.activity.address,
      price:$scope.activity.price,
      amount:$scope.activity.amount,
      status:$scope.activity.status,
      icons: $scope.activity.icons,
      content:Yihu.util.replaceLazyHtml($scope.activity.contentBody),
      summary: $scope.activity.summary,
      sign_upCount: $scope.activity.sign_upCount
    };
    ActivityService.update({id: $state.params.id}, form, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.activity.icons.push({ id: id, width: width, height: height, 
              thWidth: { width: box.data("thwidthWidth") || "", height: box.data("thwidthHeight") || ""}, 
              thHeight: { width: box.data("thheightWidth") || "", height: box.data("thheightHeight") || ""} 
            });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      type: "image",
      path: "/activity"
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
  });
});

/**
 * 产品款式管理模块
 */
var productModelsListModule = angular.module("ProductModelsListModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns']);
productModelsListModule.controller('ProductModelsListCtrl', function($scope, $state, uiGridConstants, myModal,ProductModelsService, $rootScope){
  $scope.productModels = {};
  $scope.ProductModelsForm = {
    title:'产品款式管理'
  };

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };

  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });

    init();
  };
   
  $scope.gridOptions.columnDefs = [{
      field: 'name',
      displayName: '产品款式名称'
    },{
      field: 'price',
      displayName: '价格',
      type:'number'
    },{
      name: 'width',
      displayName: '尺寸',
      cellTemplate: '<span>{{row.entity.width}}{{row.entity.unit}} x {{row.entity.height}}{{row.entity.unit}}</span>',
      enableFiltering: false
    }, {
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/products/models/'+ $state.params.id+'/edit/{{COL_FIELD}}">修改</a>',
      enableFiltering: false
    }
  ];

  var getPage = function() {
    var form = {
      name: $scope.productModels.name
    };

    ProductModelsService.getList({
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize,
      pid: $state.params.id || ""
    }, form, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      $scope.gridOptions.data = data.artworkModels || [];
    });
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if($rootScope.nestedAnimated){
      $rootScope.nestedAnimated = false;
      $rootScope.currentAnimated = false;
    }else if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  $scope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $rootScope.nestedAnimated = true;
    $state.go('^');
  };

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        ProductModelsService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };

})
.controller('AddProductModelsCtrl', function($scope, $rootScope, $state, $timeout, ProductModelsService, Upload, Pid, myModal, FileManagerService, dateFilter){
  $scope.ModelForm = {
    title:"新增产品款式"
  };

  $scope.models = {};
  $scope.models.icons = [];
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?h=180',''), title: $scope.models.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.models.icons.splice(i, 1);
      }
    });
  };

  $timeout(function(){
    $scope.models.pid = Pid || "";

    init();
  });

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级'  },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.models.icons.push({ id: id, width: width, height: height, 
              thWidth: { width: box.data("thwidthWidth") || "", height: box.data("thwidthHeight") || ""}, 
              thHeight: { width: box.data("thheightWidth") || "", height: box.data("thheightHeight") || ""} 
            });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = "/product";
  function getList(){
    var opts = {
      order:"name",
      desc:1,
      // type:"image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
  });

  // upload on file select or drop
  $scope.upload = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    if (files && files.length) {
      $scope.showDialog = true;

      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.models.icons.push({
                id: data.id, 
                width: data.width,
                height: data.height,
                thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
                thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };

  $scope.submitForm = function(){
    var form = {
      name: $scope.models.name,
      price: $scope.models.price,
      width: $scope.models.width,
      height: $scope.models.height,
      unit: $scope.models.unit,
      icons: $scope.models.icons,
      pid: $scope.models.pid
    };

    ProductModelsService.create(form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditProductModelsCtrl', function($scope, $rootScope, $state, $timeout, ProductModelsService, Models, Upload, myModal, FileManagerService, dateFilter){
  $scope.ModelForm = {
    title:"更新产品款式"
  };

  $scope.models = Models || {};
  var icons = $scope.icons = [];
  $scope.images = [];

  var watcher = $scope.$watch("models.name", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        $scope.models = Models;

        if($scope.models.icons){
          for(var i=0; i<$scope.models.icons.length; i++){
            var p = $scope.models.icons[i];
            var pid = $scope.models.icons[i].id;
            $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?h=180"),width: p.width, height: p.height});
          }
        }else{
          $scope.models.icons = [];
        }

        init();
      }, 50);
    }
  });

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?h=180',''), title: $scope.models.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.models.icons.splice(i, 1);
      }
    });
  };

  // upload on file select or drop
  $scope.upload = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    if (files && files.length) {
      $scope.showDialog = true;

      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.models.icons.push({
                id: data.id, 
                width: data.width,
                height: data.height,
                thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
                thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级'  },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.models.icons.push({ id: id, width: width, height: height, 
              thWidth: { width: box.data("thwidthWidth") || "", height: box.data("thwidthHeight") || ""}, 
              thHeight: { width: box.data("thheightWidth") || "", height: box.data("thheightHeight") || ""} 
            });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order:"name",
      desc:1,
      // type:"image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
  });

  $scope.submitForm = function(){
    var form = {
      name: $scope.models.name,
      price: $scope.models.price,
      width: $scope.models.width,
      height: $scope.models.height,
      unit: $scope.models.unit,
      icons: $scope.models.icons,
      pid: $scope.models.pid
    };

    ProductModelsService.update({id: $state.params.mid}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^', {id: $scope.models.pid});
    });
  };

  $rootScope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $state.go('^', {id: $scope.models.pid});
  };
});

/**
 * 订单管理模块
 */
var orderListModule = angular.module("OrderListModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns']);
orderListModule.controller('OrderListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, $rootScope, OrderService, $timeout, Store) {
  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true,
    showMenu:false
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };

  $scope.exportExcelUrl = 'about:blank';
  $scope.exportExcel = function() {    
    var form = {
      currentPage:paginationOptions.pageNumber, 
      orderNo: $scope.orders.orderNo || '',
      startDate: $('#beginCreateTime').val(),
      endDate: $('#endCreateTime').val(),
      status: $scope.orders.status,
      type: $scope.orders.type,
      userId: $scope.orders.userId || -1,
      receiver: $scope.orders.receiver || ''
    };
    $scope.exportExcelUrl = `http://pe1975mall.yihuyixi.com/cms/order/list/excel?currentPage=1&pageSize=10000&orderNo=${form.orderNo}&startDate=${form.startDate}&endDate=${form.endDate}&status=${form.status}&type=${form.type}&userId=${form.userId}&receiver=${form.receiver}`;
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi;
    if ($stateParams.reset) {
      $scope.orders.type = '-1';
      $scope.orders.status = $stateParams.status || '-1';
      Store.localRemove('orderSearch');
    } else {
      var lastSearch = JSON.parse(Store.localGet('orderSearch') || '{}');
      paginationOptions.pageNumber = lastSearch.currentPage || 1; 
      paginationOptions.pageSize = lastSearch.pageSize; 
      $scope.orders.orderNo = lastSearch.orderNo || '';
      $('#beginCreateTime').val(lastSearch.startDate || '');
      $('#endCreateTime').val(lastSearch.endDate || '');
      $scope.orders.userId = lastSearch.userId || '-1';
      $scope.orders.receiver = lastSearch.receiver || '';
      $scope.orders.type = lastSearch.type || '-1';
      $scope.orders.status = lastSearch.status || '-1';
      $scope.gridOptions.paginationCurrentPage = paginationOptions.pageNumber;
    }

    $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
      if (sortColumns.length === 0) {
        paginationOptions.sort = null;
      }else{
        paginationOptions.sort = sortColumns[0].sort.direction;
      }
      getPage();
    });

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'orderNo',
      displayName: '订单号',
      width:150
    },{
      field: 'type',
      displayName: '订单类型',
      cellFilter:'mapOrderType',
      width: 80
    },{
      field: 'totalFee',
      displayName: '实付金额',
      type: 'number',
      width: 80
    },{
      field: 'couponFee',
      displayName: '优惠券抵扣',
      type: 'number',
      width: 90
    },{
      field: 'discount',
      displayName: '商家折扣',
      type: 'number',
      width: 80
    },{
      field: 'status',
      displayName: '订单状态',
      cellFilter:'mapOrderStatus',
      width: 80
    },{
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/orders/{{row.entity.id}}">处理订单</a>',
      enableFiltering: false,
      width: 120
    },{
      field: 'createAt',
      displayName: '下单时间',
      width:150
    },{
      field: 'userId',
      displayName: '下单用户',
      width:80
    },{
      field: 'title',
      displayName: '订单描述',
      width:200
    },{
      field: 'express.deliverAt',
      displayName: '发货时间',
      width:150
    },{
      field: 'express.receiver',
      displayName: '收件人',
      width:90
    },{
      field: 'express.mobile',
      displayName: '联系方式',
      width:120
    },{
      field: 'express.expressAddress',
      displayName: '收件地址',
      width: 250
    }
  ];

  $scope.orders = {
    statusList: [{
      text: '全部', value: -1
    },{
      text: '待付款', value: 0
    },{
      text: '待发货', value: 1
    },{
      text: '待收货', value: 2
    },{
      text: '已完成', value: 3
    },{
      text: '已取消', value: 4
    }],
    typeList: [{
      text: '全部', value: -1
    }, {
      text: '有货订单', value: 0
    },{
      text: '预定订单', value: 1
    },{
      text: '秒杀订单', value: 3
    },{
      text: '团购订单', value: 4
    },{
      text: '拍卖订单', value: 5
    },{
      text: '充值订单', value: 6
    },{
      text: '首单特惠', value: 7
    },{
      text: '拼团订单', value: 8
    },{
      text: '砍价助力', value: 9
    },{
      text: '拼团直购', value: 10
    }]
  };
  // var typeParam = $state.params.type || -1;
  // if(typeParam >= -1) {
  //   $scope.orders.status = typeParam + '';
  // }

  //分页查询
  var getPage = function() {
    var form = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize,
      orderNo: $scope.orders.orderNo || '',
      startDate: $('#beginCreateTime').val(),
      endDate: $('#endCreateTime').val(),
      status: $scope.orders.status,
      type: $scope.orders.type,
      userId: $scope.orders.userId || -1,
      receiver: $scope.orders.receiver || ''
    };
    OrderService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var orders = data.orders || [];
      angular.forEach(orders, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm:ss");        
        if(item.express && item.express.deliverAt) {
          item.express.deliverAt = moment(item.express.deliverAt).format("YYYY-MM-DD HH:mm:ss");
        }else{
          if (item.express && item.status !== 3) {
            item.express.deliveryAt = "暂未发货";
          } else if (item.status !== 3) {
            item.express = {"deliverAt": "暂未发货"};
          }
        }
      });
      $scope.gridOptions.data = orders;
      Store.localSave('orderSearch', JSON.stringify(form));
    });
  };

  $scope.changeOrderType = function() {
    $stateParams.type = $scope.orders.type || -1;
  }

  $scope.changeOrderStatus = function() {
    $stateParams.status = $scope.orders.status || -1;
  }
  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;
        OrderService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.filter('mapOrderStatus', function(){
  var orderStatusHash = {
    0:'待付款',
    1:'待发货',
    2:'待收货',
    3:'已完成',
    4:'已取消',
    5:'申请退款',
    6:'退款中',    
    7:'已退款',
    8:'退款失败'
  };
  return function(input){
    if(input < 0){
      return 'Unknown';
    }
    return orderStatusHash[input];
  };
})
.filter('mapOrderType', function(){
  var orderTypeHash = {
    0:'有货订单',
    1:'预定订单',
    3:'秒杀订单',
    4:'团购订单',
    5:'拍卖订单',
    6:'充值订单',
    7:'首单特惠',
    8:'拼团订单',
    9:'砍价助力',
    10:'拼团直购',
    100: '售货机订单'
  };
  return function(input){
    return orderTypeHash[input];
  };
})
.controller('OrderViewCtrl', function($scope, $state, $timeout, $rootScope, Order, OrderService, BasicService, FileManagerService, Upload){
  $scope.Form = {
    title:"订单处理"
  };  

  $scope.orders = Order || {};
  var watcher = $scope.$watch("orders", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        $scope.orders.createAt = moment($scope.orders.createAt).format("YYYY-MM-DD HH:mm:ss");
        if(!$scope.orders.express){
          $scope.orders.express = {"deliverAt": "暂未发货"};
        } else if($scope.orders.express.deliverAt) {
          $scope.orders.express.deliverAt = moment($scope.orders.express.deliverAt).format("YYYY-MM-DD HH:mm:ss");
        }else{
          $scope.orders.express.deliverAt = "暂未发货";
        }
        if ($scope.orders.receiverAt){
          $scope.orders.receiverAt = moment($scope.orders.receiverAt).format("YYYY-MM-DD HH:mm:ss");
        }
        if ($scope.orders.refund) {
          if ($scope.orders.refund.userStage && $scope.orders.refund.userStage.createTime) {
            $scope.orders.refund.userStage.createTime = moment($scope.orders.refund.userStage.createTime).format("YYYY-MM-DD HH:mm:ss");
          }
          if ($scope.orders.refund.finishStage && $scope.orders.refund.finishStage.createTime) {
            $scope.orders.refund.finishStage.createTime = moment($scope.orders.refund.finishStage.createTime).format("YYYY-MM-DD HH:mm:ss");
          }
          if ($scope.orders.refund.auditStage && $scope.orders.refund.auditStage.createTime) {
            $scope.orders.refund.auditStage.createTime = moment($scope.orders.refund.auditStage.createTime).format("YYYY-MM-DD HH:mm:ss");
          }
        }
        if ($scope.orders.user) {
          if ($scope.orders.user.nickName) {
            $scope.orders.user.userName = Base64.decode($scope.orders.user.nickName);
          } else {
            $scope.orders.user.userName = '匿名';
          }
          if ($scope.orders.user.firstView) {
            $scope.orders.user.firstViewTime = moment($scope.orders.user.firstView).format("YYYY-MM-DD HH:mm");
          } else {
            $scope.orders.user.firstViewTime = '';
          }
        }
      }, 50);
      BasicService.getExpressList(function(data){
        $scope.orders.expressList = (data && data.childrens) || [];
      });
    }
  });
  $scope.pictures = [];
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: '发货图片',width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.pictures.splice(i, 1);
      }
    });
  };

  // upload on files select or drop
  $scope.upload  = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };

    if (files && files.length) {
      $scope.showDialog = true;

      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            uploadedCallback(fileItem.fileName, fileItem);
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.pictures.push(data.id);
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };

  function uploadedCallback(fileName, fileItem){
    var form = {
      path: '/product/默认库', 
      fileName: fileName,
      fileType: guessFileType(fileName),
      picture: {
        width: fileItem.width,
        height: fileItem.height,
        thWidth: { width: fileItem.thWidth && fileItem.thWidth.width, height: fileItem.thWidth && fileItem.thWidth.height},
        thHeight: { width: fileItem.thHeight && fileItem.thHeight.width, height: fileItem.thHeight && fileItem.thHeight.height},
        id: fileItem.id
      }
    };

    FileManagerService.mkdir({}, form, function(data){
      console.log(data);
    });
  }

  $timeout(function(){
    $scope.loadDeliveryLog();
  }, 2000);

  $scope.loadDeliveryLog = function() {
    OrderService.getDeliveryLog({orderNo: $scope.orders.orderNo}, function(res) {
      if (res.result == 0) {
        var list = res.data || [];
        angular.forEach(list, function(item){
          item.operateTime = moment(item.operateTime).format("YYYY-MM-DD HH:mm:ss");
        });
        $scope.deliverlog = list;
      }
    });
  };

  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if($scope.orders.express && $scope.orders.express.deliverAt === '暂未发货'){
      $scope.orders.express.deliverAt = "";
    }
  });

  $scope.editPrice = function(){
    $scope.orders.editPrice = true;
  };
  $scope.savePrice = function(){
    $scope.orders.editPrice = false;
    OrderService.updatePrice({
      id: $scope.orders.id,
      discount: $scope.orders.discountAmount
    }, function(res){
      if(res.result === 0){
        $rootScope.$window.location.reload(true);
      }
    });
  };
  $scope.discardEditPrice = function(){
    $scope.orders.editPrice = false;
  };

  $scope.orders.wxNotify = 'true';
  $scope.readyDelivery = function(){
    $scope.orders.deliveryGoods = true;
  };
  
  $scope.doDelivery = function(){
    $scope.orders.deliveryGoods = false;
    OrderService.deliveryGoods({
      id: $scope.orders.id,
      openid: $scope.orders.openid,
      express: {
        expressCompany: $("select[name='expressComany']").find("option:selected").text(),
        expressNo: $scope.orders.express.expressNo,
        expressCode: $scope.orders.express.expressCode,
        recommend: $scope.orders.express.recommend || '',
        gift: $scope.orders.express.gift || '',
        remark: $scope.orders.express.remark || '',
        fee: $scope.orders.express.fee || 0,
        internalRemark: $scope.orders.express.internalRemark || ''
      },
      deliverLog: {
        orderNo: $scope.orders.orderNo,
        operator: $scope.currentUser.userName,
        deliverNo: $scope.orders.express.expressNo,
        deleiverFee: $scope.orders.express.fee || 0,
        deliverCompany: $("select[name='expressComany']").find("option:selected").text(),
        pics: $scope.pictures,
        status: $scope.orders.deliveryStatus || 1,
        remark: $scope.orders.express.remark || ''
      },
      url: '/#/order/' + $scope.orders.orderNo,
      wxNotify: $("input[name='wxNotify']").prop('checked') || false
    }, function(res){
      if(res.result === 0){
        $scope.loadDeliveryLog();
        $rootScope.currentAnimated = !$rootScope.currentAnimated;
        $state.go('^', {type: $scope.orders.status});
      }
    });
  };
  $scope.cancelDelivery = function(){
    $scope.orders.deliveryGoods = false;
  };

  $scope.readyDelay = function(){
    $scope.orders.delayDelivery = true;
  };
  $scope.sendDelayMsg = function(){
    $scope.orders.delayDelivery = false;
    OrderService.orderDelay({
      openid: $scope.orders.openid,
      orderNo: $scope.orders.orderNo,
      totalFee: $scope.orders.totalFee,
      username: $scope.orders.express.receiver,
      remark: $scope.orders.delayReason,
      url: '/#/order/' + $scope.orders.orderNo,
      deliverLog: {
        orderNo: $scope.orders.orderNo,
        operator: $scope.currentUser.userName,
        deliverNo: '',
        deleiverFee: 0,
        deliverCompany: '',
        pics: [],
        status: 2,
        remark: '[延迟发货提醒]: ' + $scope.orders.delayReason
      }
    }, function(res){
      if(res.result === 0){
        $rootScope.$window.location.reload(true);
      }
    });
  };
  $scope.cancelDelayMsg = function(){
    $scope.orders.delayDelivery = false;
  };

  $scope.orders.refundAmount = '1';
  $scope.orders.refundMethod = '原路返回';
  $scope.orders.refunds = false;
  
  $scope.refund = function(){
    $scope.orders.refunds = true;
  };
  $scope.doRefund = function(){
    $scope.orders.refunds = false;
    OrderService.refund({
      openid: $scope.orders.openid,
      orderNo: $scope.orders.orderNo,
      refund: {
        auditStage: {
          desc: $scope.orders.refundComment,
          userId: $scope.currentUser.userId
        }
      }
    }, function(res){
      if(res.result === 0){
        $scope.orders.status = 6;
        $rootScope.$window.location.reload(true);
      } else {
        alert("退款失败！原因：" + res.message);
      }
    });
  };
  $scope.rejectRefund = function(){
    $scope.orders.refunds = false;
    OrderService.rejectRefund({
      openid: $scope.orders.openid,
      orderNo: $scope.orders.orderNo,
      refund: {
        auditStage: {
          desc: $scope.orders.refundComment,
          userId: $scope.currentUser.userId
        }
      }
    }, function(res){
      if(res.result === 0){
        $scope.orders.status = 1;
        $rootScope.$window.location.reload(true);
      }
    });
  };
  $scope.cancelRefund = function(){
    $scope.orders.refunds = false;
  };

  $scope.closeOrder = function(){
    OrderService.closeOrder({
      orderNo: $scope.orders.orderNo
    }, function(res){
      if(res.result === 0){
        $scope.orders.status = 3;
        $rootScope.$window.location.reload(true);
      }
    });
  };

  $scope.orders.orderStatus = '订单提醒';
  $scope.orders.platform = 'weixin';
  $scope.openAnnouceMsg = function(){
    $scope.orders.annouceMsg = true;
    if ($scope.orders.user.follow == 1) {
      $scope.orders.platform = 'weixin';
    } else {
      $scope.orders.platform = 'mobile';
    }
  };
  $scope.sendAnnouceMsg = function(){
    $scope.orders.annouceMsg = false;
    $scope.orders.orderStatus = '订单提醒';
    var msg = $scope.orders.remark || '';
    if ($scope.orders.first) {
      msg += ('[微信通知]：' + $scope.orders.first || '');
    }
    if (!$("input[name='platform']").prop('checked')) {
      msg += ('[手机短信]：' + $scope.orders.smsMsg || '');
    }
    OrderService.annouceOrderMsg({
      orderNo: $scope.orders.orderNo,
      openid: $scope.orders.openid,
      date: $scope.orders.createAt,
      status: $scope.orders.orderStatus,
      name: $scope.orders.title,
      first: $scope.orders.first,
      remark: $scope.orders.remark,
      sendMsg: $("input[name='platform']").prop('checked') ? false : true,
      message: $scope.orders.smsMsg || '',
      deliverLog: {
        orderNo: $scope.orders.orderNo,
        operator: $scope.currentUser.userName,
        deliverNo: $scope.orders.express.expressNo,
        deleiverFee: $scope.orders.express.fee || 0,
        deliverCompany: $scope.orders.express.expressNo ? $("select[name='expressComany']").find("option:selected").text() : '',
        pics: $scope.pictures,
        status: $scope.orders.deliveryStatus || 2,
        remark: msg
      }
    }, function(res){
      if(res.result == 0){
        var sms = data.message;
        var wechat = data.wechat;
        var errmsg = '';
        if (sms && !sms.success) {
          errmsg += ' 短信发送失败：' + sms.msg;
        }
        if (wechat && wechat.errcode) {
          errmsg += ' 微信发送失败：' + wechat.errmsg;
        }
        if (errmsg) {
          alert('发送失败，原因：' + errmsg);
        } else {
          alert("订单受理提醒发送成功！");
          $scope.loadDeliveryLog();
        }
      } else {
        alert('网络故障，请稍候再试！');
      }
    });
  };
  $scope.cancelAnnounceMsg = function(){
    $scope.orders.annouceMsg = false;
  };
  
  $scope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $rootScope.nestedAnimated = true;
    $state.go('^');
  };
})
.controller('OrderPrintCtrl', function($scope, $state, $timeout, $rootScope, Order, OrderService){
  $scope.Form = {
    title:"打印商品清单"
  };  

  $scope.orders = Order || {};
  var watcher = $scope.$watch("orders", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        $scope.orders.createAt = moment($scope.orders.createAt).format("YYYY-MM-DD HH:mm:ss");
      }, 50);
    }
  });
  
  $scope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $rootScope.nestedAnimated = true;
    $state.go('^');
  };
})
.controller('OrderTrackExpressCtrl', function($scope, $state, $timeout, $rootScope, Order, OrderService){
  $scope.Form = {
    title:"物流跟踪"
  };  

  $scope.orders = Order || {};
  var watcher = $scope.$watch("orders", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        OrderService.trackExpress({
          expressNo: $scope.orders.express.expressNo,
          expressCode: $scope.orders.express.expressCode
        }, function(res){
          if(res.list){
            $scope.expressLogs = res.list;
          }else{
            $scope.errors = res.msg;
          }
        });
      }, 50);
    }
  });

  $scope.discard = function(){
    $rootScope.currentAnimated = !$rootScope.currentAnimated;
    $rootScope.nestedAnimated = true;
    $state.go('^');
  };

});

/**
 * 秒杀模块
 * @type {[type]}
 */
var seckillModule = angular.module("SeckillModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ngFileUpload']); 
seckillModule.controller('SeckillListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, SeckillService, $rootScope) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'name',
      displayName: '秒杀商品',
      width:380
    },{
      field: 'price',
      displayName: '市场价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'killPrice',
      displayName: '秒杀价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'stock',
      displayName: '初始库存',
      width:80
    },{
      field: 'number',
      displayName: '剩余库存',
      width:80
    },{
      field: 'status',
      displayName: '秒杀状态'
    },{
      field: 'startTime',
      displayName: '起止时间',
      cellTemplate: '<span>{{COL_FIELD}} ~ {{row.entity.endTime}}</span>',
      enableFiltering: false,
      width:320
    },{
      field: 'createTime',
      displayName: '创建时间',
      width:190
    },{
      name: 'seckillId',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/seckill/{{COL_FIELD}}/edit">修改</a>&nbsp;&nbsp;<a class="btn-small" href="#/seckill/{{COL_FIELD}}/successkilled">秒杀成功列表</a>',
      enableFiltering: false
    }
  ];

  $scope.seckill = {};

  //分页查询
  var getPage = function() {
    var form = {
      pageIndex:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize,
      name: $scope.seckill.name || ''
    };
    SeckillService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.total || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var list = data.list || [];
      var now = new Date();
      angular.forEach(list, function(item){
        if(new Date(item.endTime) < now){
          item.status = '已结束';
        }else if(new Date(item.startTime) > now){
          item.status = '即将开始';
        }else{
          item.status = '抢购中';
        }
        item.createTime = moment(item.createTime).format("YYYY-MM-DD HH:mm:ss");
        item.startTime = moment(item.startTime).format("YYYY-MM-DD HH:mm:ss");
        item.endTime = moment(item.endTime).format("YYYY-MM-DD HH:mm:ss");
      });
      $scope.gridOptions.data = list;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.seckillId;

        SeckillService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.controller('AddSeckillCtrl', function($scope, $state, $timeout, SeckillService, Upload, $rootScope, myModal, FileManagerService){
  $scope.SeckillForm = {
    title:"新增秒杀商品"
  };
  
  $scope.seckill = {
  };

  $timeout(function(){
    init();
  });

  $scope.seckill.icon = '';
  var icons = $scope.icons = [];
  $scope.images = [];
  $scope.addIcon = function(icon){
    icons.splice(0, icons.length);
    icons.push(icon);
    
    $scope.images.splice(0, $scope.images.length);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.seckill.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.seckill.icon = '';
      }
    });
  };

  var watcher = $rootScope.$watch("choosedProduct", function(newValue, oldValue){
    var product = $rootScope.choosedProduct;
    $scope.seckill.goodsId = product.id || '';
    $scope.seckill.name = product.name || '';
    $scope.seckill.price = product.price || 0;
    $scope.seckill.icon = '';
    $scope.seckill.sellPoint = product.sellPoint;
    var pid = product.pictures && product.pictures[0].id;
    if(pid){
      $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
      $scope.seckill.icon = pid;
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.seckill.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var form = {
      name:$scope.seckill.name,
      startTime:$("#startTime").val(),
      endTime:$("#endTime").val(),
      price:$scope.seckill.price,
      killPrice:$scope.seckill.killPrice,
      number:$scope.seckill.number,
      icon: $scope.seckill.icon,
      goodsId: $scope.seckill.goodsId,
      sellPoint: $scope.seckill.sellPoint || ''
    };

    SeckillService.create({}, form, function(data){
      if(data.success){
        SeckillService.startupSeckillTask({}, {
          pid: data.data.seckillId,
          type: 0,
          startDate: moment($("#startTime").val()).format("YYYY-MM-DD HH:mm")
        }, function(res){
          console.log(res);
        });
      }
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.seckill.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.choosedProduct = {};
  });
})
.controller('EditSeckillCtrl', function($scope, $state, $timeout, SeckillService, Seckill, Upload, $rootScope, myModal, FileManagerService){
  $scope.SeckillForm = {
    title:"修改秒杀商品"
  };

  var icons = $scope.icons = [];
  $scope.images = [];
  $scope.addIcon = function(icon){
    icons.splice(0, icons.length);
    icons.push(icon);
    
    $scope.images.splice(0, $scope.images.length);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.seckill.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };
  
  $scope.seckill = (Seckill && Seckill.data) || {};
  var watcher = $rootScope.$watch("choosedProduct.id", function(newValue, oldValue){
    if(newValue){
      var product = $rootScope.choosedProduct;
      $scope.seckill.goodsId = product.id || '';
      $scope.seckill.icon = '';
      $scope.seckill.sellPoint = product.sellPoint;
      var pid = product.pictures && product.pictures[0].id;
      if(pid){
        $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        $scope.seckill.icon = pid;
      }
    }
  });
  var watcher2 = $scope.$watch("seckill", function(newVal, oldValue){
    if(newVal){
      watcher2();
      init();

      $timeout(function(){
        var seckill = (Seckill && Seckill.data);
        $scope.seckill.goodsId = seckill.goodsId;
        $scope.seckill.icon = seckill.icon;
        var pid = $scope.seckill.icon;
        if(pid){
          $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        }
      }, 50);
    }
  });

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.seckill.icon = '';
      }
    });
  };

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.seckill.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var form = {
      name:$scope.seckill.name,
      startTime:$("#startTime").val(),
      endTime:$("#endTime").val(),
      price:$scope.seckill.price,
      killPrice:$scope.seckill.killPrice,
      stock:$scope.seckill.stock,
      number:$scope.seckill.number,
      icon: $scope.seckill.icon,
      goodsId: $scope.seckill.goodsId,
      seckillId: $scope.seckill.seckillId,
      sellPoint: $scope.seckill.sellPoint || ''
    };

    SeckillService.update({id: $scope.seckill.seckillId}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.seckill.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.choosedProduct = {};
  });
})
.controller('SuccessKilledListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, SeckillService, $rootScope) {
  $scope.Form = {
    title:"秒杀成功列表"
  };

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    getPage();
  };
  
  $scope.seckill = {};
  $scope.gridOptions.columnDefs = [{
      field: 'seckillId',
      displayName: '秒杀商品ID'
    },{
      field: 'userId',
      displayName: '用户ID'
    },{
      field: 'userName',
      displayName: '用户名'
    },{
      field: 'status',
      displayName: '交易状态',
      cellFilter: 'mapSeckillStatus'
    },{
      field: 'createTime',
      displayName: '交易时间'
    }
  ];

  //分页查询
  var getPage = function() {
    var form = {
      offset:paginationOptions.pageNumber, 
      limit:paginationOptions.pageSize,
      seckillId: $stateParams.id || 0,
      userId: $scope.seckill.userId || ''
    };
    SeckillService.getSuccessKilledList(form, function(data){
      $scope.gridOptions.totalItems = data.total || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var list = data.list || [];
      angular.forEach(list, function(item){
        item.createTime = moment(item.createTime).format("YYYY-MM-DD HH:mm:ss");
      });
      $scope.gridOptions.data = list;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    $("#myModal").remove();

    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

})
.filter('mapSeckillStatus', function(){
  var statusHash = {
    0:'未付款',
    1:'已完成',
    2:'已失效'
  };
  return function(input){
    return statusHash[input];
  };
});

/**
 * 优惠券管理模块
 * @type {[type]}
 */
var couponModule = angular.module("CouponModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ngFileUpload']); 
couponModule.controller('CouponListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, CouponService, $rootScope) {
  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.coupon = {};
  $scope.gridOptions.columnDefs = [{
      field: 'provideTitle',
      displayName: '活动名称',
      width: 280
    },{
      field: 'payValue',
      displayName: '发行面值',
      width: 80
    },{
      field: 'provideTotal',
      displayName: '发行张数',
      width: 100
    },{
      field: 'receiveTotal',
      displayName: '已领张数',
      width: 100
    },{
      field: 'provideName',
      displayName: '发行方',
      width: 100
    },{
      field: 'public',
      displayName: '是否公开',
      width: 80
    },{
      field: 'desc',
      displayName: '活动描述'
    },{
      field: 'createAt',
      displayName: '创建时间'
    },{
      name: 'id',
      displayName: '操作',
      width: 240,
      cellTemplate: '<a class="btn-small" href="#/coupon/{{COL_FIELD}}/edit">修改</a>&nbsp;&nbsp;<a class="btn-small" href="#/coupon/{{COL_FIELD}}/detail">查看详情</a>&nbsp;&nbsp;<a ng-if="row.entity.publishids" class="btn-small" href="#/coupon/{{COL_FIELD}}/addmember">添加成员</a>',
      enableFiltering: false
    }
  ];

  //分页查询
  var getPage = function() {
    var form = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      provideTitle: $scope.coupon.provideTitle || ''
    };
    CouponService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var list = data.qrCodes || [];
      angular.forEach(list, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm:ss");
        item.provideName = item.provideId ? '代理商' + (item.provideId) : '官方';
      });
      $scope.gridOptions.data = list;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();
    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        CouponService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };

})
.controller('AddCouponCtrl', function($scope, $state, CouponService, $rootScope, $timeout, Unsaved){
  $scope.Form = {
    title:"新增优惠券活动"
  };
  $scope.coupon = {
    isPublic:'true',
    type: '0'
  };
  var watcher = $scope.$watch("coupon.content", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        if(Unsaved.content){
          $scope.coupon.id = Unsaved.id;
          $scope.coupon.content = Unsaved.content;
        }
        $scope.coupon.content = Yihu.util.restoreRawHtml($scope.coupon.content);
      }, 50);
    }
  });

  $scope.submitForm = function(){
    var form = {
      provideTitle: $scope.coupon.provideTitle,
      provideTotal: $scope.coupon.provideTotal,
      provideId: $scope.coupon.provideId || 0,
      payValue: $scope.coupon.payValue,
      desc: $scope.coupon.desc,
      type: $scope.coupon.type,
      public:$("input[name='isPublic']").prop('checked'),
      content:Yihu.util.replaceLazyHtml($scope.coupon.contentBody)
    };
    CouponService.create({}, form, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditCouponCtrl', function($scope, $state, CouponService, $rootScope, $timeout, Coupon, Unsaved){
  $scope.Form = {
    title:"修改优惠券活动"
  };
  $scope.coupon = Coupon || {};
  var watcher = $scope.$watch("coupon.content", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.coupon = Coupon || {};
      if(Unsaved.content){
        $scope.coupon.content = Unsaved.content;
      }
      $scope.coupon.content = Yihu.util.restoreRawHtml($scope.coupon.content);
      $scope.coupon.isPublic = Coupon.public+'';
      $scope.coupon.type = Coupon.type;
    }, 50);
  });
  $scope.submitForm = function(){
    var form = {
      provideTitle: $scope.coupon.provideTitle,
      provideTotal: $scope.coupon.provideTotal,
      payValue: $scope.coupon.payValue,
      desc: $scope.coupon.desc,
      type: $scope.coupon.type,
      public:$("input[name='isPublic']").prop('checked'),
      content:Yihu.util.replaceLazyHtml($scope.coupon.contentBody)
    };
    CouponService.update({id: $state.params.id}, form, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('ViewCouponCtrl', function($scope, $state, CouponService, $rootScope, $timeout, Coupon, Config){
  $scope.Form = {
    title:"查看优惠券活动"
  };
  $scope.coupon = Coupon || {};
  var watcher = $scope.$watch("coupon.content", function(newValue, oldValue){
    watcher();

    $timeout(function(){
      $scope.coupon = Coupon || {};
      var ids = $scope.coupon.gridfsids;
      if(!$scope.coupon.publishids && ids.length) {
        $scope.coupon.qrcode = Config.profiles[Config.env].context + '/qrcode/download/' + ids[0].gridfsid;
      }
      CouponService.getCoupons({
        qrcodeid: $scope.coupon.id
      }, function(data) {
        var stats = {};
        for(var i=0, len=data.length; i<len; i++) {
          var agentId = data[i].agentId;
          if (stats[agentId]) {
            stats[agentId].count++;
          } else {
            var nickname = data[i].nickName;
            stats[agentId] = {count: 1, nickName: nickname ? Base64.decode(nickname) : agentId };
          }
        }
        $scope.coupon.agentStats = stats;
      });
    }, 50);
  });
})
.controller('AddGroupCouponCtrl', function($scope, $state, CouponService, $rootScope, $timeout, Unsaved, UserService){
  $scope.Form = {
    title:"新增群组优惠券活动"
  };
  $scope.coupon = {};
  $scope.left = {
    title: '用户列表',
    items:[]
  };
  $scope.right = {
    title: '已选用户',
    items:[]
  };
  var watcher = $scope.$watch("coupon", function(newVal, oldVal){
    if(newVal){
      watcher();

      $timeout(function(){
        if(Unsaved.content){
          $scope.coupon.id = Unsaved.id;
          $scope.coupon.content = Unsaved.content;
        }
        $scope.coupon.content = Yihu.util.restoreRawHtml($scope.coupon.content);
      }, 50);
    }
  });
  $timeout(function(){
    UserService.getList({currentPage:1, pageSize: 5000}, function(data){
      var items = data.users || [];
      var leftItems = [];
      angular.forEach(items, function(item){
        if (item.userName || item.nickName) {
          leftItems.push({text: item.userName || item.nickName + '(微信用户)', value: item.userId});
        }
      });
      $scope.left.items = leftItems;
    });
  }, 800);

  $scope.submitForm = function(){
    var selectedUsers = $("select[name='rightItem']>option").map(function(){ 
      return $(this).val(); }
    ).get();

    var form = {
      provideTitle: $scope.coupon.provideTitle,
      provideTotal: $scope.coupon.provideTotal,
      provideId: $scope.coupon.provideId || 0,
      payValue: $scope.coupon.payValue,
      desc: $scope.coupon.desc,
      content:Yihu.util.replaceLazyHtml($scope.coupon.contentBody),
      publishids: selectedUsers
    };
    CouponService.createGroupCoupon({}, form, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('AddCouponGroupMemberCtrl', function($scope, $state, CouponService, $rootScope, $timeout, UserService, Coupon){
  $scope.Form = {
    title:"新增群组成员"
  };
  $scope.coupon = Coupon || {};
  $scope.left = {
    title: '用户列表',
    items:[]
  };
  $scope.right = {
    title: '已选用户',
    items:[]
  };
  var watcher = $scope.$watch("coupon.content", function(newVal, oldVal){
    if(newVal){
      watcher();
      $scope.coupon = Coupon || {};
    }
  });
  $timeout(function(){
    var rightItems = [];
    var uniqueItems = [];
    angular.forEach($scope.coupon.publishids, function(item){
      uniqueItems.push(item);
    });

    UserService.getList({currentPage:1, pageSize: 5000}, function(data){
      var items = data.users || [];
      var leftItems = [];
      angular.forEach(items, function(item){
        if (item.userName || item.nickName) {
          if($.inArray(item.userId, uniqueItems)<0){
            leftItems.push({text: item.userName || item.nickName + '(微信用户)', value: item.userId});
          } else {
            rightItems.push({text: item.userName || item.nickName + '(微信用户)', value: item.userId});
          }
        }
      });
      $scope.right.items = rightItems;
      $scope.left.items = leftItems;
    });
  }, 800);

  $scope.submitForm = function(){
    var selectedUsers = $("select[name='rightItem']>option").map(function(){ 
      return $(this).val(); }
    ).get();

    var form = {
      id: $scope.coupon.id,
      publishids: selectedUsers
    };
    CouponService.addGroupMember({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
});


/**
 * 团购模块
 * @type {[type]}
 */
var groupBuyModule = angular.module("GroupBuyModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ngFileUpload']); 
groupBuyModule.controller('GroupBuyListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, GroupBuyService, $rootScope) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'name',
      displayName: '团购名称',
      width:380
    },{
      field: 'oldPrice',
      displayName: '市场价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'groupPrice',
      displayName: '团购价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'moq',
      displayName: '起订量',
      width:80
    },{
      field: 'bookmoq',
      displayName: '已预定量',
      width:80
    },{
      field: 'status',
      displayName: '团购状态',
      cellFilter:'mapGroupbuyStatus'
    },{
      field: 'startDate',
      displayName: '起止时间',
      cellTemplate: '<span>{{COL_FIELD}} ~ {{row.entity.endDate}}</span>',
      enableFiltering: false,
      width:320
    },{
      field: 'createAt',
      displayName: '创建时间',
      width:190
    },{
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/groupbuy/{{COL_FIELD}}/edit">修改</a>',
      enableFiltering: false
    }
  ];

  $scope.groupbuy = {};

  //分页查询
  var getPage = function() {
    var form = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      name: $scope.groupbuy.name || ''
    };
    GroupBuyService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var list = data.groupBuies || [];
      angular.forEach(list, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm");
        item.startDate = moment(item.startDate).format("YYYY-MM-DD HH:mm");
        item.endDate = moment(item.endDate).format("YYYY-MM-DD HH:mm");
      });
      $scope.gridOptions.data = list;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        GroupBuyService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.filter('mapGroupbuyStatus', function(){
  var statusHash = {
    0:'待上线',
    1:'正在进行',
    2:'已结束',
    3:'已删除'
  };
  return function(input){
    return statusHash[input];
  };
})
.controller('AddGroupBuyCtrl', function($scope, $state, $timeout, GroupBuyService, Upload, $rootScope, myModal, FileManagerService, Unsaved, SeckillService){
  $scope.Form = {
    title:"新增团购商品"
  };
  
  $scope.groupbuy = {};
  $timeout(function(){
    init();
    $scope.groupbuy.id = Unsaved.id;
    if(Unsaved.content){
      $scope.groupbuy.content = Unsaved.content;
    }
    $scope.groupbuy.content = Yihu.util.restoreRawHtml($scope.groupbuy.content);
  }, 200);

  $scope.groupbuy.icon = '';
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.groupbuy.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.groupbuy.icon = '';
      }
    });
  };

  var watcher = $rootScope.$watch("choosedProduct", function(newValue, oldValue){
    var product = $rootScope.choosedProduct;
    $scope.groupbuy.artworkId = product.id || '';
    $scope.groupbuy.name = product.name || '';
    $scope.groupbuy.oldPrice = product.price || 0;
    $scope.groupbuy.icon = '';
    var pid = product.pictures && product.pictures[0].id;
    if(pid){
      $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
      $scope.groupbuy.icon = pid;
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.groupbuy.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var form = {
      strStartDate: $("#strStartDate").val(),
      strEndDate: $("#strEndDate").val(),
      name: $scope.groupbuy.name,
      sumary: $scope.groupbuy.sumary,
      rule: Yihu.util.replaceLazyHtml($scope.groupbuy.ruleBody),
      description: Yihu.util.replaceLazyHtml($scope.groupbuy.contentBody),
      icon: $scope.groupbuy.icon,
      moq: $scope.groupbuy.moq,
      bookmoq: $scope.groupbuy.bookmoq,
      artwork: {
        id: $scope.groupbuy.artworkId
      },
      groupPrice: $scope.groupbuy.groupPrice,
      oldPrice: $scope.groupbuy.oldPrice
    };

    GroupBuyService.create({}, form, function(data){
      $scope.$emit('clean.autosave');
      if(data.result === 0){
        SeckillService.startupSeckillTask({}, {
          pid: data.primaryId,
          type: 2,
          startDate: moment($("#strStartDate").val()).format("YYYY-MM-DD HH:mm")
        }, function(res){
          console.log(res);
        });
      }
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.groupbuy.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.choosedProduct = {};
  });
})
.controller('EditGroupBuyCtrl', function($scope, $state, $timeout, GroupBuyService, Upload, $rootScope, myModal, FileManagerService, Unsaved, Groupbuy){
  $scope.Form = {
    title:"修改团购商品"
  };
  
  $scope.groupbuy = Groupbuy || {};
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.splice(0, icons.length);
    icons.push(icon);

    $scope.images.splice(0, $scope.images.length);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.groupbuy.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.groupbuy.icon = '';
      }
    });
  };

  var watcher = $rootScope.$watch("choosedProduct.id", function(newValue, oldValue){
    if(newValue){
      var product = $rootScope.choosedProduct;
      $scope.groupbuy.artworkId = product.id || '';
      $scope.groupbuy.icon = '';
      var pid = product.pictures && product.pictures[0].id;
      if(pid){
        $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        $scope.groupbuy.icon = pid;
      }
    }
  });
  var watcher2 = $scope.$watch("groupbuy", function(newVal, oldValue){
    if(newVal){
      watcher2();
      init();

      $timeout(function(){
        var groupbuy = Groupbuy || {};
        $scope.groupbuy.artworkId = groupbuy.artwork.id;
        $scope.groupbuy.icon = groupbuy.icon;
        var pid = $scope.groupbuy.icon;
        if(pid){
          $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        }
        if(Unsaved.content){
          $scope.groupbuy.description = Unsaved.content;
        }
        $scope.groupbuy.content = Yihu.util.restoreRawHtml($scope.groupbuy.description);
        $scope.groupbuy.rule = Yihu.util.restoreRawHtml($scope.groupbuy.rule);
        $scope.groupbuy.strStartDate = moment($scope.groupbuy.startDate).format("YYYY-MM-DD HH:mm:ss");
        $scope.groupbuy.strEndDate = moment($scope.groupbuy.endDate).format("YYYY-MM-DD HH:mm:ss");
      }, 50);
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.groupbuy.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var form = {
      strStartDate: $("#strStartDate").val(),
      strEndDate: $("#strEndDate").val(),
      name: $scope.groupbuy.name,
      sumary: $scope.groupbuy.sumary,
      rule: Yihu.util.replaceLazyHtml($scope.groupbuy.ruleBody),
      description: Yihu.util.replaceLazyHtml($scope.groupbuy.contentBody),
      icon: $scope.groupbuy.icon,
      moq: $scope.groupbuy.moq,
      bookmoq: $scope.groupbuy.bookmoq,
      artwork: {
        id: $scope.groupbuy.artworkId
      },
      groupPrice: $scope.groupbuy.groupPrice,
      oldPrice: $scope.groupbuy.oldPrice,
      id: $scope.groupbuy.id
    };

    GroupBuyService.update({}, form, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.groupbuy.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.choosedProduct = {};
  });
});

/**
 * 首单特惠模块
 * @type {[type]}
 */
var firstpayModule = angular.module("FirstpayModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ngFileUpload']); 
firstpayModule.controller('FirstpayListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, FirstpayService, $rootScope) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'name',
      displayName: '特惠名称',
      width:380
    },{
      field: 'fieldPrice',
      displayName: '市场价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'buttomFee',
      displayName: '首单价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'stock',
      displayName: '库存',
      width:80
    },{
      field: 'status',
      displayName: '状态',
      cellFilter: 'mapFirstpayState'
    },{
      field: 'createAt',
      displayName: '创建时间',
      width:190
    },{
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/firstpay/{{COL_FIELD}}/edit">修改</a>',
      enableFiltering: false
    }
  ];

  $scope.firstpay = {};

  //分页查询
  var getPage = function() {
    var form = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      name: $scope.firstpay.name || '',
      type: 3
    };
    FirstpayService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.total || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var list = data.list || [];
      angular.forEach(list, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm");
      });
      $scope.gridOptions.data = list;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        FirstpayService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.filter('mapFirstpayState', function(){
  var states = {
    0:'售卖中',
    1:'已售罄',
    2:'补货中',
    3:'已下架'
  };
  return function(input){
    return states[input];
  };
})
.controller('AddFirstpayCtrl', function($scope, $state, $timeout, FirstpayService, Upload, $rootScope, myModal, FileManagerService, Unsaved, SeckillService){
  $scope.Form = {
    title:"新增首单商品"
  };
  
  $scope.firstpay = {
    content: '&nbsp;'
  };
  $timeout(function(){
    init();
    $scope.firstpay.id = Unsaved.id;
    if(Unsaved.content){
      $scope.firstpay.content = Unsaved.content;
    }
    $scope.firstpay.content = Yihu.util.restoreRawHtml($scope.firstpay.content);
  }, 200);

  $scope.firstpay.icon = '';
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.firstpay.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.firstpay.icon = '';
      }
    });
  };

  var watcher = $rootScope.$watch("choosedProduct", function(newValue, oldValue){
    var product = $rootScope.choosedProduct;
    $scope.firstpay.artworkId = product.id || '';
    $scope.firstpay.name = product.name || '';
    $scope.firstpay.fieldPrice = product.price || 0;
    $scope.firstpay.icon = '';
    $scope.firstpay.sellPoint = product.sellPoint;
    var pid = product.pictures && product.pictures[0].id;
    if(pid){
      $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
      $scope.firstpay.icon = pid;
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.firstpay.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var form = {
      name: $scope.firstpay.name,
      rule: Yihu.util.replaceLazyHtml($scope.firstpay.contentBody),
      fieldPrice: $scope.firstpay.fieldPrice,
      buttomFee: $scope.firstpay.buttomFee,
      icon: $scope.firstpay.icon,
      stock: $scope.firstpay.stock,
      artworkId: $scope.firstpay.artworkId,
      creator: $scope.currentUser.userId,
      sellPoint: $scope.firstpay.sellPoint || '',
      type: 3
    };

    FirstpayService.create({}, form, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.firstpay.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.choosedProduct = {};
  });
})
.controller('EditFirstpayCtrl', function($scope, $state, $timeout, FirstpayService, Upload, $rootScope, myModal, FileManagerService, Unsaved, Firstpay){
  $scope.Form = {
    title:"修改首单商品"
  };
  
  $scope.firstpay = Firstpay || {};
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.splice(0, icons.length);
    icons.push(icon);

    $scope.images.splice(0, $scope.images.length);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.firstpay.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.firstpay.icon = '';
      }
    });
  };

  var watcher = $rootScope.$watch("choosedProduct.id", function(newValue, oldValue){
    if(newValue){
      var product = $rootScope.choosedProduct;
      $scope.firstpay.artworkId = product.id || '';
      $scope.firstpay.icon = '';
      $scope.firstpay.sellPoint = product.sellPoint;
      var pid = product.pictures && product.pictures[0].id;
      if(pid){
        $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        $scope.firstpay.icon = pid;
      }
    }
  });
  var watcher2 = $scope.$watch("firstpay", function(newVal, oldValue){
    if(newVal){
      watcher2();
      init();

      $timeout(function(){
        var firstpay = Firstpay || {};
        $scope.firstpay.artworkId = firstpay.artworkId;
        $scope.firstpay.icon = firstpay.icon;
        var pid = $scope.firstpay.icon;
        if(pid){
          $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        }
        $scope.firstpay.content = Yihu.util.restoreRawHtml(firstpay.rule);
        $scope.firstpay.status = firstpay.status + '';
      }, 50);
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.firstpay.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var form = {
      name: $scope.firstpay.name,
      rule: Yihu.util.replaceLazyHtml($scope.firstpay.contentBody),
      icon: $scope.firstpay.icon,
      stock: $scope.firstpay.stock,
      fieldPrice: $scope.firstpay.fieldPrice,
      buttomFee: $scope.firstpay.buttomFee,
      artworkId: $scope.firstpay.artworkId,
      sellPoint: $scope.firstpay.sellPoint || '',
      id: $scope.firstpay.id,
      status: $scope.firstpay.status,
      creator: $scope.currentUser.userId,
      type: 3
    };

    FirstpayService.update({}, form, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.firstpay.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.choosedProduct = {};
  });
});

/**
 * 分享特惠模块
 * @type {[type]}
 */
var sharepayModule = angular.module("SharepayModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ngFileUpload']); 
sharepayModule.controller('SharepayListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, FirstpayService, $rootScope) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'name',
      displayName: '特惠名称',
      width:380
    },{
      field: 'fieldPrice',
      displayName: '市场价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'buttomFee',
      displayName: '底价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'forwardFee',
      displayName: '每次减价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'stock',
      displayName: '库存',
      width:80
    },{
      field: 'cutHours',
      displayName: '砍价时长',
      cellTemplate: '<span>{{COL_FIELD || 0}}小时</span>',
      width: 130
    },{
      field: 'status',
      displayName: '状态',
      cellFilter: 'mapFirstpayState'
    },{
      field: 'createAt',
      displayName: '创建时间',
      width:190
    },{
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/sharepay/{{COL_FIELD}}/edit">修改</a>',
      enableFiltering: false
    }
  ];

  $scope.sharepay = {};

  //分页查询, type目前支持3种， 1：分享特惠， 2：拼团  3：首单特惠
  var getPage = function() {
    var form = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      name: $scope.sharepay.name || '',
      type: 1
    };
    FirstpayService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.total || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var list = data.list || [];
      angular.forEach(list, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm");
      });
      $scope.gridOptions.data = list;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        FirstpayService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.filter('mapFirstpayState', function(){
  var states = {
    0:'售卖中',
    1:'已售罄',
    2:'补货中',
    3:'已下架'
  };
  return function(input){
    return states[input];
  };
})
.controller('AddSharepayCtrl', function($scope, $state, $timeout, FirstpayService, Upload, $rootScope, myModal, FileManagerService, Unsaved, SeckillService, DataDictService){
  $scope.Form = {
    title:"新增砍价商品"
  };
  
  $scope.sharepay = {
    cutHours: 168
  };
  $timeout(function(){
    init();
    $scope.sharepay.id = Unsaved.id;
    $scope.loadHardRates();
    // if(Unsaved.content){
    //   $scope.sharepay.content = Unsaved.content;
    // }
    // $scope.sharepay.content = Yihu.util.restoreRawHtml($scope.sharepay.content);
  }, 200);

  $scope.sharepay.icon = '';
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.loadHardRates = function(){
    DataDictService.getChildren({
      parentPath: 'cms/config/bargain/hardrate'
    }, function(data){
      $scope.sharepay.hardRates = data.childrens;
    });
  };

  $scope.changeHardRates = function() {
    var desc = $("select[name='difficulty']").find("option:selected").attr("key");
    if (desc) {
      $scope.sharepay.secret = desc;
    } else {
      $scope.sharepay.secret = '';
    }
  }

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.sharepay.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.sharepay.icon = '';
      }
    });
  };

  var watcher = $rootScope.$watch("choosedProduct", function(newValue, oldValue){
    var product = $rootScope.choosedProduct;
    $scope.sharepay.artworkId = product.id || '';
    $scope.sharepay.name = product.name || '';
    $scope.sharepay.fieldPrice = product.price || 0;
    $scope.sharepay.icon = '';
    $scope.sharepay.sellPoint = product.sellPoint;
    var pid = product.pictures && product.pictures[0].id;
    if(pid){
      $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
      $scope.sharepay.icon = pid;
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.firstpay.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var relatedBargainGoods = $rootScope.selectedBargainGoods || [];
    var related = [];
    angular.forEach(relatedBargainGoods, function(item, i){
      related.push({
        "fieldId": item.fieldId || item.id,
        "fieldPrice": item.fieldPrice,
        "buttomFee": item.buttomFee,
        "createAt": item.createAt,
        "name": item.name,
        "icon": item.icon,
        "status": item.status,
        "sellPoint": item.sellPoint,
        "forwardFee": item.forwardFee
      });
    });
    var form = {
      name: $scope.sharepay.name,
      rule: '', //Yihu.util.replaceLazyHtml($scope.sharepay.contentBody),
      fieldPrice: $scope.sharepay.fieldPrice,
      buttomFee: $scope.sharepay.buttomFee,
      forwardFee: $scope.sharepay.forwardFee,
      specialPrice: $scope.sharepay.fieldPrice,
      icon: $scope.sharepay.icon,
      stock: $scope.sharepay.stock,
      cutHours: $scope.sharepay.cutHours,
      sellPoint: $scope.sharepay.sellPoint || '',
      artworkId: $scope.sharepay.artworkId,
      creator: $scope.currentUser.userId,
      type: 1,
      relates: related,
      difficulty: $scope.sharepay.difficulty,
      secret: $scope.sharepay.secret
    };

    FirstpayService.create({}, form, function(data){
      // $scope.$emit('clean.autosave');
      // if(data.result === 0){
      //   SeckillService.startupSeckillTask({}, {
      //     pid: data.primaryId,
      //     type: 2,
      //     startDate: moment($("#strStartDate").val()).format("YYYY-MM-DD HH:mm")
      //   }, function(res){
      //     console.log(res);
      //   });
      // }
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.sharepay.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };
  $scope.removeBargain = function(idx) {
    if ($rootScope.selectedBargainGoods && $rootScope.selectedBargainGoods.length > idx) {
      $rootScope.selectedBargainGoods.splice(idx, 1);
    }
  };
  $scope.cleanBargainGoods = function() {
    $rootScope.selectedBargainGood = {};
    $rootScope.multiSelectBarginGoods = [];
    $rootScope.selectedBargainGoods = [];
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.multiSelectBarginGoods = [];
    $rootScope.selectedBargainGoods = [];
    $rootScope.choosedProduct = {};
    $rootScope.multiSelectProducts = [];
  });
})
.controller('EditSharepayCtrl', function($scope, $state, $timeout, FirstpayService, Upload, $rootScope, myModal, FileManagerService, Unsaved, Sharepay, DataDictService){
  $scope.Form = {
    title:"修改砍价商品"
  };
  
  $scope.sharepay = Sharepay || {};
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.loadHardRates = function(){
    DataDictService.getChildren({
      parentPath: 'cms/config/bargain/hardrate'
    }, function(data){
      $scope.sharepay.hardRates = data.childrens;
      $timeout(function() {
        $scope.sharepay.newDifficulty = $scope.sharepay.difficulty || '';
      }, 100);
    });
  };

  $scope.changeHardRates = function() {
    var desc = $("select[name='difficulty']").find("option:selected").attr("key");
    if (desc) {
      $scope.sharepay.secret = desc;
    } else {
      $scope.sharepay.secret = '';
    }
  }

  $scope.addIcon = function(icon){
    icons.splice(0, icons.length);
    icons.push(icon);

    $scope.images.splice(0, $scope.images.length);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.sharepay.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.sharepay.icon = '';
      }
    });
  };

  var watcher = $rootScope.$watch("choosedProduct.id", function(newValue, oldValue){
    if(newValue){
      var product = $rootScope.choosedProduct;
      $scope.sharepay.artworkId = product.id || '';
      $scope.sharepay.icon = '';
      $scope.sharepay.sellPoint = product.sellPoint;
      var pid = product.pictures && product.pictures[0].id;
      if(pid){
        $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        $scope.sharepay.icon = pid;
      }
    }
  });
  var watcher2 = $scope.$watch("sharepay", function(newVal, oldValue){
    if(newVal){
      watcher2();
      init();
      $scope.loadHardRates();

      $timeout(function(){
        var sharepay = Sharepay || {};
        $scope.sharepay.artworkId = sharepay.artworkId;
        $scope.sharepay.icon = sharepay.icon;
        var pid = $scope.sharepay.icon;
        if(pid){
          $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        }
        // $scope.sharepay.content = Yihu.util.restoreRawHtml(sharepay.rule);
        $scope.sharepay.status = sharepay.status + '';
        if (Sharepay.relates && Sharepay.relates.length) {
          $rootScope.selectedBargainGoods = Sharepay.relates;
        } else {
          $rootScope.selectedBargainGoods = [];
        }
      }, 50);
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.sharepay.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var relatedBargainGoods = $rootScope.selectedBargainGoods || [];
    var related = [];
    angular.forEach(relatedBargainGoods, function(item, i){
      related.push({
        "fieldId": item.fieldId || item.id,
        "fieldPrice": item.fieldPrice,
        "buttomFee": item.buttomFee,
        "createAt": item.createAt,
        "name": item.name,
        "icon": item.icon,
        "status": item.status,
        "sellPoint": item.sellPoint,
        "forwardFee": item.forwardFee
      });
    });
    var form = {
      name: $scope.sharepay.name,
      rule: '', //Yihu.util.replaceLazyHtml($scope.sharepay.contentBody),
      icon: $scope.sharepay.icon,
      stock: $scope.sharepay.stock,
      fieldPrice: $scope.sharepay.fieldPrice,
      buttomFee: $scope.sharepay.buttomFee,
      forwardFee: $scope.sharepay.forwardFee,
      specialPrice: $scope.sharepay.fieldPrice,
      sellPoint: $scope.sharepay.sellPoint || '',
      artworkId: $scope.sharepay.artworkId,
      // cutHours: $scope.sharepay.cutHours,
      id: $scope.sharepay.id,
      status: $scope.sharepay.status,
      creator: $scope.currentUser.userId,
      type: 1,
      relates: related,
      difficulty: $scope.sharepay.newDifficulty,
      secret: $scope.sharepay.secret
    };

    FirstpayService.update({}, form, function(data){
      // $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.sharepay.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };
  $scope.removeBargain = function(idx) {
    if ($rootScope.selectedBargainGoods && $rootScope.selectedBargainGoods.length > idx) {
      $rootScope.selectedBargainGoods.splice(idx, 1);
    }
  };
  $scope.cleanBargainGoods = function() {
    $rootScope.selectedBargainGood = {};
    $rootScope.multiSelectBarginGoods = [];
    $rootScope.selectedBargainGoods = [];
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.multiSelectBarginGoods = [];
    $rootScope.selectedBargainGoods = [];
    $rootScope.choosedProduct = {};
    $rootScope.multiSelectProducts = [];
  });
});

/**
 * 拼团管理模块
 * @type {[type]}
 */
var tuanModule = angular.module("TuanModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ngFileUpload']); 
tuanModule.controller('TuanListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, FirstpayService, $rootScope) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'name',
      displayName: '拼团名称',
      width:380
    },{
      field: 'fieldPrice',
      displayName: '市场价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'buttomFee',
      displayName: '拼团价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'limitCount',
      displayName: '拼团人数',
      width:190
    },{
      field: 'stock',
      displayName: '库存',
      width:80
    },{
      field: 'status',
      displayName: '状态',
      cellFilter: 'mapFirstpayState'
    },{
      field: 'startDate',
      displayName: '起止时间',
      cellTemplate: '<span>{{COL_FIELD}} ~ {{row.entity.endDate}}</span>',
      enableFiltering: false,
      width:320
    },{
      field: 'createAt',
      displayName: '创建时间',
      width:190
    },{
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/tuan/{{COL_FIELD}}/edit">修改</a>',
      enableFiltering: false
    }
  ];

  $scope.tuan = {};

  //分页查询
  var getPage = function() {
    var form = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize, 
      name: $scope.tuan.name || '',
      type: 2
    };
    FirstpayService.getList(form, function(data){
      $scope.gridOptions.totalItems = data.total || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var list = data.list || [];
      angular.forEach(list, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm");
        if (item.startDate) {
          item.startDate = moment(item.startDate).format("YYYY-MM-DD HH:mm:ss");
        }
        if (item.endDate) {
          item.endDate = moment(item.endDate).format("YYYY-MM-DD HH:mm:ss");
        }
      });
      $scope.gridOptions.data = list;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        FirstpayService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.controller('AddTuanCtrl', function($scope, $state, $timeout, FirstpayService, Upload, $rootScope, myModal, FileManagerService, Unsaved, SeckillService){
  $scope.Form = {
    title:"新增拼团"
  };
  
  $scope.tuan = {
    content: '&nbsp;'
  };
  $timeout(function(){
    init();
    $scope.tuan.id = Unsaved.id;
    if(Unsaved.content){
      $scope.tuan.content = Yihu.util.restoreRawHtml(Unsaved.content);
    }
  }, 200);

  $scope.tuan.icon = '';
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.tuan.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.tuan.icon = '';
      }
    });
  };

  var watcher = $rootScope.$watch("choosedProduct", function(newValue, oldValue){
    var product = $rootScope.choosedProduct;
    $scope.tuan.artworkId = product.id || '';
    $scope.tuan.name = product.name || '';
    $scope.tuan.fieldPrice = product.price || 0;
    $scope.tuan.icon = '';
    $scope.tuan.sellPoint = product.sellPoint;
    var pid = product.pictures && product.pictures[0].id;
    if(pid){
      $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
      $scope.tuan.icon = pid;
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.tuan.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var form = {
      name: $scope.tuan.name,
      rule: Yihu.util.replaceLazyHtml($scope.tuan.contentBody),
      fieldPrice: $scope.tuan.fieldPrice,
      buttomFee: $scope.tuan.buttomFee,
      limitCount: $scope.tuan.limitCount,
      strStartDate:$("#startTime").val(),
      strEndDate:$("#endTime").val(),
      icon: $scope.tuan.icon,
      stock: $scope.tuan.stock,
      artworkId: $scope.tuan.artworkId,
      creator: $scope.currentUser.userId,
      sellPoint: $scope.tuan.sellPoint || '',
      type: 2
    };

    FirstpayService.create({}, form, function(data){
      $scope.$emit('clean.autosave');
      // if(data.result === 0){
      //   SeckillService.startupSeckillTask({}, {
      //     pid: data.primaryId,
      //     type: 2,
      //     startDate: moment($("#strStartDate").val()).format("YYYY-MM-DD HH:mm")
      //   }, function(res){
      //     console.log(res);
      //   });
      // }
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.tuan.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.choosedProduct = {};
  });
})
.controller('EditTuanCtrl', function($scope, $state, $timeout, FirstpayService, Upload, $rootScope, myModal, FileManagerService, Unsaved, Tuan){
  $scope.Form = {
    title:"修改拼团"
  };
  
  $scope.tuan = Tuan || {};
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.splice(0, icons.length);
    icons.push(icon);

    $scope.images.splice(0, $scope.images.length);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.tuan.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.tuan.icon = '';
      }
    });
  };

  var watcher = $rootScope.$watch("choosedProduct.id", function(newValue, oldValue){
    if(newValue){
      var product = $rootScope.choosedProduct;
      $scope.tuan.artworkId = product.id || '';
      $scope.tuan.icon = '';
      $scope.tuan.sellPoint = product.sellPoint;
      var pid = product.pictures && product.pictures[0].id;
      if(pid){
        $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        $scope.tuan.icon = pid;
      }
    }
  });
  var watcher2 = $scope.$watch("tuan", function(newVal, oldValue){
    if(newVal){
      watcher2();
      init();

      $timeout(function(){
        var tuan = Tuan || {};
        $scope.tuan.artworkId = tuan.artworkId;
        $scope.tuan.icon = tuan.icon;
        var pid = $scope.tuan.icon;
        if(pid){
          $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        }
        $scope.tuan.content = Yihu.util.restoreRawHtml(tuan.rule);
        $scope.tuan.status = tuan.status + '';
        if (tuan.startDate) {
          $scope.tuan.strStartDate = moment(tuan.startDate).format("YYYY-MM-DD HH:mm");
        }
        if (tuan.endDate) {
          $scope.tuan.strEndDate = moment(tuan.endDate).format("YYYY-MM-DD HH:mm");
        }
      }, 50);
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.tuan.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var form = {
      name: $scope.tuan.name,
      rule: Yihu.util.replaceLazyHtml($scope.tuan.contentBody),
      icon: $scope.tuan.icon,
      stock: $scope.tuan.stock,
      fieldPrice: $scope.tuan.fieldPrice,
      buttomFee: $scope.tuan.buttomFee,
      limitCount: $scope.tuan.limitCount,
      artworkId: $scope.tuan.artworkId,
      strStartDate:$("#startTime").val(),
      strEndDate:$("#endTime").val(),
      id: $scope.tuan.id,
      status: $scope.tuan.status,
      creator: $scope.currentUser.userId,
      sellPoint: $scope.tuan.sellPoint || '',
      type: 2
    };

    FirstpayService.update({}, form, function(data){
      $scope.$emit('clean.autosave');
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.tuan.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.choosedProduct = {};
  });
});

/**
 * 拍卖模块
 * @type {[type]}
 */
var auctionModule = angular.module("AuctionModule", ['ui.grid.pagination', 'ui.grid.selection','ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ngFileUpload']); 
auctionModule.controller('AuctionListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, AuctionService, $rootScope) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'name',
      displayName: '拍品名称',
      width:380
    },{
      field: 'startPrice',
      displayName: '起拍价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'minPrice',
      displayName: '保留价',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'markup',
      displayName: '加价幅度',
      cellTemplate: '<span>¥{{COL_FIELD}}</span>',
    },{
      field: 'auction_product_state_id',
      displayName: '拍卖状态',
      cellFilter: 'mapAuctionState'
    },{
      field: 'countAppr',
      displayName: '出价次数',
    }, {
      field: 'startTime',
      displayName: '起止时间',
      cellTemplate: '<span>{{COL_FIELD}} ~ {{row.entity.endTime}}</span>',
      enableFiltering: false,
      width:320
    },{
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/auction/{{COL_FIELD}}/edit">修改</a>&nbsp;&nbsp;<a class="btn-small" href="#/auction/{{COL_FIELD}}/prices">出价列表</a>',
      enableFiltering: false
    }
  ];

  $scope.auction = {};

  //分页查询
  var getPage = function() {
    var form = {
      paging:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize,
      name: $scope.auction.name || '',
      state: 1
    };
    AuctionService.getList(form, {}, function(data){
      $scope.gridOptions.totalItems = data.info && data.info.total || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var list = data.info && data.info.apList || [];
      angular.forEach(list, function(item){
        item.startTime = moment(item.startTime).format("YYYY-MM-DD HH:mm:ss");
        item.endTime = moment(item.endTime).format("YYYY-MM-DD HH:mm:ss");
      });
      $scope.gridOptions.data = list;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        AuctionService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.filter('mapAuctionState', function(){
  var states = {
    0:'预展',
    1:'拍卖中',
    2:'拍卖暂停',
    3:'拍卖结束',
    4:'流拍'
  };
  return function(input){
    return states[input];
  };
})
.controller('AddAuctionCtrl', function($scope, $state, $timeout, AuctionService, Upload, $rootScope, myModal, FileManagerService, Unsaved){
  $scope.Form = {
    title:"新增拍卖商品"
  };
  
  $scope.auction = {
  };

  $timeout(function(){
    init();
    $scope.auction.id = Unsaved.id;
    if(Unsaved.content){
      $scope.auction.content = Unsaved.content;
    }
    $scope.auction.content = Yihu.util.restoreRawHtml($scope.auction.content);
  }, 200);

  $scope.auction.icon = '';
  var icons = $scope.icons = [];
  $scope.images = [];
  $scope.addIcon = function(icon){
    icons.splice(0, icons.length);
    icons.push(icon);
    
    $scope.images.splice(0, $scope.images.length);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.auction.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.auction.icon = '';
      }
    });
  };

  var watcher = $rootScope.$watch("choosedProduct", function(newValue, oldValue){
    var product = $rootScope.choosedProduct;
    $scope.auction.productId = product.id || '';
    $scope.auction.name = product.name || '';
    $scope.auction.icon = '';
    var pid = product.pictures && product.pictures[0].id;
    if(pid){
      $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
      $scope.auction.icon = pid;
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.auction.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var form = {
      name:$scope.auction.name,
      startTime:$("#startTime").val(),
      endTime:$("#endTime").val(),
      startPrice: $scope.auction.startPrice,
      minPrice: $scope.auction.minPrice,
      markup: $scope.auction.markup,
      icon: $scope.auction.icon,
      productId: $scope.auction.productId,
      content: $scope.auction.contentBody,
      rule: $scope.auction.ruleBody
    };

    AuctionService.create({}, form, function(data){
      if (data.result === 0) {
        AuctionService.startupTask({}, {
          pid: data.info.id,
          type: 1,
          startDate: moment($("#startTime").val()).format("YYYY-MM-DD HH:mm")
        }, function(res){
          console.log(res);
        });
        $rootScope.currentAnimated = !$rootScope.currentAnimated;
        $state.go('^');
      }
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.auction.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.choosedProduct = {};
  });
})
.controller('EditAuctionCtrl', function($scope, $state, $timeout, AuctionService, Upload, $rootScope, myModal, FileManagerService, Unsaved, Auction){
  $scope.Form = {
    title:"修改拍卖商品"
  };
  
  $scope.auction = Auction || {};
  if($scope.auction.startTime) {
    $scope.auction.startTime = moment($scope.auction.startTime).format("YYYY-MM-DD HH:mm:ss");
  }
  if($scope.auction.endTime){
    $scope.auction.endTime = moment($scope.auction.endTime).format("YYYY-MM-DD HH:mm:ss");
  }
  var icons = $scope.icons = [];
  $scope.images = [];
  $scope.addIcon = function(icon){
    icons.splice(0, icons.length);
    icons.push(icon);
    
    $scope.images.splice(0, $scope.images.length);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.auction.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.auction.icon = '';
      }
    });
  };

  var watcher2 = $scope.$watch("auction", function(newVal, oldValue){
    if(newVal){
      watcher2();
      init();

      $timeout(function(){
        $scope.auction = Auction || {};
        $scope.auction.artworkId = Auction.productId;
        $scope.auction.icon = Auction.icon;
        $scope.auction.name = Auction.name || '';

        if($scope.auction.startTime) {
          $scope.auction.startTime = moment($scope.auction.startTime).format("YYYY-MM-DD HH:mm:ss");
        }
        if($scope.auction.endTime){
          $scope.auction.endTime = moment($scope.auction.endTime).format("YYYY-MM-DD HH:mm:ss");
        }
        var pid = $scope.auction.icon;
        if(pid){
          $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
        }
        if(Unsaved.content){
          $scope.auction.rule = Unsaved.content;
        }
        $scope.auction.content = Yihu.util.restoreRawHtml($scope.auction.content);
        $scope.auction.rule = Yihu.util.restoreRawHtml($scope.auction.rule);
      }, 50);
    }
  });

  var watcher = $rootScope.$watch("choosedProduct.id", function(newValue, oldValue){
    var product = $rootScope.choosedProduct;
    $scope.auction.artworkId = product.id || '';
    var pid = product.pictures && product.pictures[0].id;
    if(pid){
      $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: 750, height: 560});
      $scope.auction.icon = pid;
    }
  });

  // upload on file select or drop
  $scope.upload = function (file) {
    if(!file){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };
    $scope.showDialog = true;

    uploadTask.current = 1;
    uploadTask.totalFiles = 1;
    uploadTask.inprocess = true;

    var f = file;
    f.status = 'waiting';
    uploadTask.files.push(f);

    Upload.upload({
      url: $scope.singleUploadUrl,
      data: {imgFile: file}
    }).then(function (resp) {
      var data = resp.data;
      var fileItem = data;
      uploadTask.files[0].status = (fileItem.code===0 ? 'success' : 'error');
      if(uploadTask.current == uploadTask.files.length){
        uploadTask.inprocess = false;
        uploadTask.tips = "上传完成";
      }

      if(data.code===0){
        $timeout(function(){
          $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?h=180"),width: data.width, height: data.height});
          $scope.auction.icon = data.id;
        });
      }
    }, function (resp) {
      f.status = 'error';
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      // console.log('progress: ' + progressPercentage + '% ');
      uploadTask.files[0].status = 'uploading';
      uploadTask.files[0].progress = progressPercentage;
    });
  };

  $scope.submitForm = function(){
    var form = {
      name:$scope.auction.name,
      startTime:$("#startTime").val(),
      endTime:$("#endTime").val(),
      startPrice: $scope.auction.startPrice,
      minPrice: $scope.auction.minPrice,
      markup: $scope.auction.markup,
      icon: $scope.auction.icon,
      productId: $scope.auction.artworkId,
      content: $scope.auction.contentBody,
      rule: $scope.auction.ruleBody,
      id: $state.params.id
    };

    AuctionService.update({}, form, function(data){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(selectedFile.length != 1){
            alert('请选择产品图片，且只能选择一张！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=180"),width: width, height: height});
            $scope.auction.icon = id;
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = '/product';
  function getList(){
    var opts = {
      order: "name",
      desc: 1,
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
    $rootScope.choosedProduct = {};
  });
})
.controller('PriceListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, AuctionService, $rootScope) {
  $scope.Form = {
    title:"出价列表"
  };

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    getPage();
  };
  
  $scope.auction = {};
  $scope.gridOptions.columnDefs = [{
      field: 'userNameId',
      displayName: '用户ID'
    },{
      field: 'userName',
      displayName: '用户名'
    },{
      field: 'price',
      displayName: '出价金额'
    },{
      field: 'state',
      displayName: '出价状态'
    },{
      field: 'createTime',
      displayName: '出价时间'
    }
  ];

  //分页查询
  var getPage = function() {
    var form = {
      paging:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize,
      auctionProductId: $stateParams.id || 0,
      userId: $scope.auction.userId || ''
    };
    AuctionService.getPricingList(form, function(data){
      $scope.gridOptions.totalItems = data.info && data.info.total || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var list = data.info && data.info.apprList || [];
      angular.forEach(list, function(item){
        item.createTime = moment(item.createTime).format("YYYY-MM-DD HH:mm:ss");
      });
      $scope.gridOptions.data = list;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    $("#myModal").remove();

    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

})
.controller('InventoryListCtrl', function($scope, $state, $stateParams, uiGridConstants, myModal, InventoryService, $rootScope) {

  var paginationOptions = {
    pageNumber:1,
    pageSize:20,
    sort:null
  };

  $scope.gridOptions = {
    paginationPageSizes: [10, 20, 50, 100],
    paginationPageSize: 20,
    useExternalPagination: true,
    // useExternalSorting: true,
    enableSorting: false,
    showGridFooter: true,
    enableGridMenu: true,
    enableFiltering: false,
    enableRowSelection: true,
    enableSelectAll: true,
    multiSelect:true    
  };

  //搜索
  $scope.search = function(){
    paginationOptions.pageNumber = 1;
    $scope.gridOptions.paginationCurrentPage = 1;
    getPage();
  };
  
  $scope.gridOptions.onRegisterApi = function(gridApi){
    $scope.gridApi = gridApi; 

    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
      paginationOptions.pageNumber = newPage;
      paginationOptions.pageSize = pageSize;
      getPage();
    });
    init();
  };
  
  $scope.gridOptions.columnDefs = [{
      field: 'name',
      displayName: '商品名称',
      width:380
    },{
      field: 'buyPrice',
      displayName: '成本价',
      type:'number',
      width:100
    },{
      field: 'markPrice',
      displayName: '市场价',
      type:'number',
      width:100
    },{
      field: 'stock',
      displayName: '库存数',
      type:'number',
      width:100
    },{
      field: 'status',
      displayName: '状态',
      cellFilter:'mapInventoryStatus'
    },{
      field: 'createAt',
      displayName: '创建日期',      
      type: 'date',
      width:140
    },{
      name: 'id',
      displayName: '操作',
      cellTemplate: '<a class="btn-small" href="#/inventory/edit/{{COL_FIELD}}">修改</a>',
      enableFiltering: false
    }
  ];

  $scope.inventory = {};

  //分页查询
  var getPage = function() {
    var form = {
      currentPage:paginationOptions.pageNumber, 
      pageSize:paginationOptions.pageSize,
      name: $scope.inventory.name || ''
    };
    InventoryService.getList(form, {}, function(data){
      $scope.gridOptions.totalItems = data.totalRecords || 0;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      var list = data.data || [];
      angular.forEach(list, function(item){
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm:ss");
      });
      $scope.gridOptions.data = list;
    });
  };


  //注册页面跳转时，执行清理执行
  $scope.$on("$destroy", function(){
    if(!$rootScope.currentAnimated){
      $rootScope.currentAnimated = true;
    }
  });

  //高级搜索
  $scope.advancedSearch = function(){
    $(".hideSearchItems").toggle();
  };

  //初始化
  function init(){
    $("#myModal").remove();

    myModal.loadTemplateUrl('template/modal/dialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.modal = {
        title: "系统提示",
        body:'<p>请确认是否删除?</p>',
        buttons:{ YES: '确定', NO: '关闭'}
      };
    });
    getPage();
  }
  
  //删除
  $scope.remove = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      if(rows && rows.length){
        $('#myModal').modal('show');
      }
    }
  };

  //删除确认
  $scope.submitConfirm = function(){
    if($scope.gridApi && $scope.gridApi.selection){
      var rows = $scope.gridApi.selection.getSelectedGridRows();
      angular.forEach(rows, function(row, index){
        var id = row.entity.id;

        InventoryService.remove({
          id:id
        }, function(){
          getPage();
        });
      });
    }
    $('#myModal').modal('hide');
  };
})
.controller('AddInventoryCtrl', function($scope, $state,$timeout, InventoryService, Upload, $rootScope, BasicService, myModal, FileManagerService, DataDictService){
  $scope.ProductForm = {
    title:"新增库存商品"
  };
  $scope.inventory = {
    statusList: [{
      id: 0, name: '已入库'
    }, {
      id: 1, name: '已上架'
    }, {
      id: 2, name: '已下架'
    }, {
      id: 3, name: '已售罄'
    }]
  };

  $timeout(function(){
    $scope.inventory.subCategoryList = [];
    $scope.inventory.status = '0';

    //加载商品类型
    BasicService.getArtworkCategory({ type: 'tea' }, function(data){
      $scope.inventory.categorys = data && data.childrens || [];
    });
    init();
  });

  $scope.filterChildCategory = function() {
    $scope.inventory.childCategoryList = [];
    $scope.inventory.sunCategoryList = [];
    $scope.inventory.childCategory = '';
    $scope.inventory.sunCategory = '';
    angular.forEach($scope.inventory.categorys, function(item){
      if(item.propertyName == $scope.inventory.category) {
        $scope.inventory.childCategoryList = item.childrens || [];
      }
    });
  };

  $scope.filterSunCategory = function() {
    $scope.inventory.sunCategoryList = [];
    $scope.inventory.sunCategory = '';
    angular.forEach($scope.inventory.childCategoryList, function(item){
      if(item.propertyName == $scope.inventory.childCategory) {
        $scope.inventory.sunCategoryList = item.childrens || [];
      }
    });
  };

  $scope.inventory.pictures = [];
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.inventory.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.inventory.pictures.splice(i, 1);
      }
    });
  };

  // upload on files select or drop
  $scope.upload  = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };

    if (files && files.length) {
      $scope.showDialog = true;

      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            uploadedCallback(fileItem.fileName, fileItem);
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.inventory.pictures.push({
                id: data.id, 
                width: data.width,
                height: data.height,
                thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
                thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };

  function uploadedCallback(fileName, fileItem){
    var form = {
      path: '/product/默认库', 
      fileName: fileName,
      fileType: guessFileType(fileName),
      picture: {
        width: fileItem.width,
        height: fileItem.height,
        thWidth: { width: fileItem.thWidth && fileItem.thWidth.width, height: fileItem.thWidth && fileItem.thWidth.height},
        thHeight: { width: fileItem.thHeight && fileItem.thHeight.width, height: fileItem.thHeight && fileItem.thHeight.height},
        id: fileItem.id
      }
    };

    FileManagerService.mkdir({}, form, function(data){
      console.log(data);
    });
  }

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=150"),width: width, height: height});
            $scope.inventory.pictures.push({ id: id, width: width, height: height, 
              thWidth: { width: box.data("thwidthWidth") || "", height: box.data("thwidthHeight") || ""}, 
              thHeight: { width: box.data("thheightWidth") || "", height: box.data("thheightHeight") || ""} 
            });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = "/product";
  function getList(){
    var opts = {
      order:"name",
      desc:1,
      // type:"image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
  });

  $scope.submitForm = function(){    
    var form = {
      name: $scope.inventory.name,
      buyPrice: $scope.inventory.buyPrice,
      markPrice: $scope.inventory.markPrice,
      category:{
        name: '',
        value: '',
        parent: {
          name: $scope.inventory.category,
          value: $("select[name='category']").find("option:selected").text()
        }
      },
      stock: $scope.inventory.stock,
      pictures:$scope.inventory.pictures
    };
    if($scope.inventory.childCategory){
      form.category.name = $scope.inventory.childCategory;
      form.category.value = $("select[name='childCategory']").find("option:selected").text();
    }
    if($scope.inventory.sunCategory){
      form.category.children = {
        name: $scope.inventory.sunCategory,
        value: $("select[name='sunCategory']").find("option:selected").text()
      };
    }
    InventoryService.create({}, form, function(){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.controller('EditInventoryCtrl', function($scope, $state,$timeout, InventoryService, Upload, $rootScope, BasicService, myModal, FileManagerService, DataDictService){
  $scope.ProductForm = {
    title:"更新库存商品"
  };
  $scope.inventory = {};
  $timeout(function() {
    InventoryService.findOne({id: $state.params.id}, function(data) {
      if (data.result == 0) {
        $scope.inventory = data.data || {};
        if($scope.inventory.pictures && $scope.inventory.pictures.length){
          for(var i=0; i<$scope.inventory.pictures.length; i++){
            var p = $scope.inventory.pictures[i];
            var pid = $scope.inventory.pictures[i].id;
            $scope.addIcon({id: pid, link: Yihu.util.setContext($scope.downloadUrl, pid+"?w=150"),width: p.width, height: p.height});
          }
        }else{
          $scope.inventory.pictures = [];
        }
        $scope.init();
        init();
      }
    });
  }, 500);

  //初始化数据
  $scope.init = function(){
    $scope.inventory.subCategoryList = [];
    $scope.inventory.statusList = [{
      id: 0, name: '已入库'
    }, {
      id: 1, name: '已上架'
    }, {
      id: 2, name: '已下架'
    }, {
      id: 3, name: '已售罄'
    }];
    var cat = $scope.inventory.category.parent && $scope.inventory.category.parent.name;
    var subCat = $scope.inventory.category.name;
    //加载商品类型
    BasicService.getArtworkCategory({ type: 'tea' }, function(data){
      $scope.inventory.categorys = data && data.childrens || [];
      angular.forEach($scope.inventory.categorys, function(item, idx){
        if(item.propertyName == cat) {
          $scope.inventory.childCategoryList = item.childrens || [];

          angular.forEach($scope.inventory.childCategoryList, function(node){
            if(node.propertyName == subCat) {
              $scope.inventory.sunCategoryList = node.childrens || [];
            }
          });
        }
      });
      
      $timeout(function(){
        $scope.inventory.status = $scope.inventory.status + '';
        $scope.inventory.childCategory = $scope.inventory.category.name;
        $scope.inventory.sunCategory = $scope.inventory.category.children && $scope.inventory.category.children.name;
        $scope.inventory.category = $scope.inventory.category.parent.name;
      }, 500);
    });
  };

  $scope.filterChildCategory = function() {
    $scope.inventory.childCategoryList = [];
    $scope.inventory.sunCategoryList = [];
    $scope.inventory.childCategory = '';
    $scope.inventory.sunCategory = '';
    angular.forEach($scope.inventory.categorys, function(item){
      if(item.propertyName == $scope.inventory.category) {
        $scope.inventory.childCategoryList = item.childrens || [];
      }
    });
  };

  $scope.filterSunCategory = function() {
    $scope.inventory.sunCategoryList = [];
    $scope.inventory.sunCategory = '';
    angular.forEach($scope.inventory.childCategoryList, function(item){
      if(item.propertyName == $scope.inventory.childCategory) {
        $scope.inventory.sunCategoryList = item.childrens || [];
      }
    });
  };

  $scope.inventory.pictures = [];
  var icons = $scope.icons = [];
  $scope.images = [];

  $scope.addIcon = function(icon){
    icons.push(icon);
    $scope.images.push({link: icon.link && icon.link.replace('?w=150',''), title: $scope.inventory.name,width: icon.width, height: icon.height});
    $scope.previewLoaded = true;

    if(!$scope.$$phase){
      $scope.$apply();
    }
  };

  $scope.removeIcon = function(icon){
    angular.forEach(icons, function(item, i){
      if(icon.link==item.link){
        icons.splice(i, 1);
        $scope.inventory.pictures.splice(i, 1);
      }
    });
  };

  // upload on files select or drop
  $scope.upload  = function (files) {
    if(!files){
      return;
    }
    var uploadTask = $scope.uploadTask = { files: [] };

    if (files && files.length) {
      $scope.showDialog = true;

      for (var i = 0; i < files.length; i++) {
        uploadTask.current = i+1;
        uploadTask.totalFiles = files.length;
        uploadTask.inprocess = true;

        var file = files[i];
        file.status = 'waiting';
        uploadTask.files.push(file);

        Upload.upload({
          url: $scope.singleUploadUrl,
          data: {imgFile: file}
        }).then(function (resp) {
          var data = resp.data;
          var fileItem = data;
          var idx = getFileIndex(uploadTask.files, {name: fileItem && fileItem.fileName});
          if(idx>=0){
            uploadTask.files[idx].status = (fileItem.code===0 ? 'success' : 'error');
          }
          if(uploadTask.current == uploadTask.files.length){
            uploadTask.inprocess = false;
            uploadTask.tips = "上传完成";
          }

          if(data.code===0){
            uploadedCallback(fileItem.fileName, fileItem);
            $timeout(function(){
              $scope.addIcon({id: data.id, link: Yihu.util.setContext($scope.downloadUrl, data.id+"?w=150"),width: data.width, height: data.height});
              $scope.inventory.pictures.push({
                id: data.id, 
                width: data.width,
                height: data.height,
                thWidth: { width: data.thWidth && data.thWidth.width, height: data.thWidth && data.thWidth.height},
                thHeight: { width: data.thHeight && data.thHeight.width, height: data.thHeight && data.thHeight.height}
              });
            });
          }
        }, function (resp) {
          file.status = 'error';
          console.log('Error status: ' + resp.status);
        }, function (evt) {
          var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
          // console.log('progress: ' + progressPercentage + '% ');
          var idx = getFileIndex(uploadTask.files, evt && evt.config._file);
          if(idx>=0){
            uploadTask.files[idx].status = 'uploading';
            uploadTask.files[idx].progress = progressPercentage;
          }
        });
      }
    }
  };

  function uploadedCallback(fileName, fileItem){
    var form = {
      path: '/product/默认库', 
      fileName: fileName,
      fileType: guessFileType(fileName),
      picture: {
        width: fileItem.width,
        height: fileItem.height,
        thWidth: { width: fileItem.thWidth && fileItem.thWidth.width, height: fileItem.thWidth && fileItem.thWidth.height},
        thHeight: { width: fileItem.thHeight && fileItem.thHeight.width, height: fileItem.thHeight && fileItem.thHeight.height},
        id: fileItem.id
      }
    };

    FileManagerService.mkdir({}, form, function(data){
      console.log(data);
    });
  }

  //初始化
  function init(){
    getList();

    myModal.loadTemplateUrl('template/modal/filesDialog.html', {scope: $scope})
    .then(function(modalDialog){
      $scope.modalDialog = modalDialog;
      $scope.dialog = {
        title: "图片库",
        buttons:{ YES: "选定", NO: "取消", BACK: '返回上一级' },
        ok:function(){
          var selectedFile = $(".file > .item-checked");
          if(!selectedFile.length){
            alert('请选择至少一张图片！');
            return;
          }
          selectedFile.each(function(i, item){
            var box = $(item);
            var id = box.data("picture");
            var width = box.data("width") || "";
            var height = box.data("height") || "";
            $scope.addIcon({id: id, link: Yihu.util.setContext($scope.downloadUrl, id+"?h=150"),width: width, height: height});
            $scope.inventory.pictures.push({ id: id, width: width, height: height, 
              thWidth: { width: box.data("thwidthWidth") || "", height: box.data("thwidthHeight") || ""}, 
              thHeight: { width: box.data("thheightWidth") || "", height: box.data("thheightHeight") || ""} 
            });
          });
          $(".file > .item-checked").removeClass("item-checked");
          $('#filesDialog').modal('hide');
        },
        goback: function() {
          var dir = $scope.path;
          var idx = dir.lastIndexOf('/');
          if (idx > 1) {
            dir = dir.substring(0, dir.lastIndexOf('/', idx));
            $scope.path = dir;
          }
          getList();
        },
        discard:function(){
          $(".file > .item-checked").removeClass("item-checked");
        }
      };
    });
  }

  $scope.path = "/product";
  function getList(){
    var opts = {
      order:"name",
      desc:1,
      // type:"image",
      path: $scope.path
    };
    FileManagerService.getList(opts, function(data){
      $scope.gridData = {};
      $scope.gridData.files = (data.info && data.info.files) || [];
      $scope.disablePrevied = true;
    });
  }

  $scope.fireAction = function(item){
    if(item.fileType == 'folder'){
      $scope.path += '/'+item.fileName;
      getList();
    }
  };

  $scope.openPhotoLibs = function(){
    $('#filesDialog').modal('show');
  };

  //清理任务
  $scope.$on("$destroy", function(){
    $("#filesDialog").remove();
  });

  $scope.submitForm = function(){    
    var form = {
      id: $state.params.id,
      name: $scope.inventory.name || '',
      buyPrice: $scope.inventory.buyPrice,
      markPrice: $scope.inventory.markPrice,
      category:{
        name: '',
        value: '',
        parent: {
          name: $scope.inventory.category,
          value: $("select[name='category']").find("option:selected").text()
        }
      },
      stock: $scope.inventory.stock,
      pictures:$scope.inventory.pictures,
      status: $scope.inventory.status
    };
    if($scope.inventory.childCategory){
      form.category.name = $scope.inventory.childCategory;
      form.category.value = $("select[name='childCategory']").find("option:selected").text();
    }
    if($scope.inventory.sunCategory){
      form.category.children = {
        name: $scope.inventory.sunCategory,
        value: $("select[name='sunCategory']").find("option:selected").text()
      };
    }
    InventoryService.update({}, form, function(){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    });
  };
})
.filter('mapInventoryStatus', function(){
  var states = {
    0:'已入库',
    1:'已上架',
    2:'已下架',
    3:'已售罄'
  };
  return function(input){
    return states[input];
  };
});

function getFileIndex(files, file){
  if(!file){
    return -1;
  }

  if(files && files.length){
    for(var i=0; i<files.length; i++){
      if(file.$$hashKey){
        if(files[i].$$hashKey==file.$$hashKey && files[i].name==file.name){
          return i;
        }
      }else{
        if(files[i].name==file.name){
          return i;
        }
      }
    }
  }
}

function guessFileType(fileName){
  if(!fileName){
    return '';
  }

  var suffix = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
  var videos = ['.mpeg','.mpg','.avi','.mov','.mpg','.mkv','.rm','.rmvb','.wmv','.asf','.mov','.mp4','.asf','.3gp','.dmv','.mtv'];
  var images = ['.jpg','.jpeg','.bmp','.png','.gif','.tiff'];
  if(videos.indexOf(suffix) >= 0){
    return "video";
  }else if(images.indexOf(suffix)>= 0){
    return "image";
  }else if(".swf"==suffix){
    return "flash";
  }
  return "file";
}